使用jQuery“点击'被装载Ajax内容的功能?功能、内容、jQuery、Ajax

2023-09-10 14:21:28 作者:月亮未能奔我而来

我有一个包含HTML和JavaScript通过Ajax加载的PHP文件的内容。我有一个按钮:

I have the contents of a php file loaded via Ajax that contains HTML and JavaScript. I have a button:

<button class="search_button">Search</button>

和我有下面的脚本会从一个jQuery函数更新文件哈希

And I have a script underneath that will update the documents hash from a jQuery function

<script type="text/javascript">
  $(".search_button").click(function() {
    var searchTerm = $('#search_box').val();         
    document.location.hash="searchTerm";
    return false;
  });
</script>

这code工作时,我单独运行PHP文件,而是从一个Ajax调用加载这个页面时,该功能不再运行。在萤火虫的脚本不是present所以我假设我不能使用这种方法加载脚本。我也尝试把JavaScript片段,而不是对整个网站的标题,但也失败了。

This code works when I run the php file separately, but when loading this page from an Ajax call, the function no longer runs. In firebug the script is not present so I am assuming I cannot load a script in using this method. I tried also putting the JavaScript snippet instead a header for the whole website, but this failed also.

我也在想也许是函数时,有一个search_button类已经present中声明,但它的结构以这种方式,当我previously让他们在一个文件中(这是通过Ajax检索)没有用,所以我很困惑的问题。

I was also thinking perhaps the function has to be declared when there is a search_button class already present, but it was structured in this way when I previously had them in one file (that was retrieved via Ajax) to no avail so I'm confused as to the problem.

推荐答案

您可以在全球包括其与现场活动:

You can include it globally with a live event:

  $(".search_button").live('click', function() {
    var searchTerm = $('#search_box').val();         
    document.location.hash="searchTerm";
    return false;
  });

jQuery将自动评估脚本块,你看不到的功能的HTML,因为它已被剥离出来。然而,它应该已经运行。问题是最有可能的时机。你可以不喜欢

jQuery will automatically evaluate script blocks, you cannot see the function in the HTML because it has been stripped out. However it should have already run. The problem is most likely timing. You could do something like

setTimeout(function(){  
    $(".search_button").click(function() {
        var searchTerm = $('#search_box').val();         
        document.location.hash="searchTerm";
        return false;
    });
}, 500);

这样当脚本加载它等待被执行(希望给jQuery的时间来更新与新元素的DOM)。

So that when the script is loaded it waits to be executed (hopefully giving jquery time to update the DOM with the new element).