将jquery绑定到动态加载的内容

sou*_*ste 2 jquery

我有以下html树:

<div class="section yellow" id="section1">
    <div id="content-wrap1" class="content-wrap">
</div>
Run Code Online (Sandbox Code Playgroud)

我使用ajax将以下内容加载到#content-wrap1:

<div id="content">
    <a href="whoweare.php">Who we are</a>
    <a href="whatwedo.php">Our team</a>
    <p>ABOUT US : Dance is a type of art</p>
</div>
Run Code Online (Sandbox Code Playgroud)

哪个成功发生,结果HTML如下所示:

<div class="section yellow" id="section1">
    <div id="content-wrap1" class="content-wrap">.
        <div id="content">
        <a href="whoweare.php">Who we are</a>
        <a href="whatwedo.php">Our team</a>
        <p>ABOUT US : Dance is a type of art</p>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

现在我想点击动态加载的链接来加载以下内容:

<div id="content">
    <a href="whoweare.php">Who we are</a>
    <a href="whatwedo.php">Our team</a>
    <p>Hi there! How are you?</p>
</div>
Run Code Online (Sandbox Code Playgroud)

所以最终的HTML看起来像这样:

<div class="section yellow" id="section1">
    <div id="content-wrap1" class="content-wrap">.
        <div id="content">
        <a href="whoweare.php">Who we are</a>
        <a href="whatwedo.php">Our team</a>
        <p>Hi there! How are you?</p>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我听说我应该使用on()jquery绑定到动态加载的内容.所以我做了以下事情:

('#section1').on("click", "#section1#content-wrap1#content a", function(){
    alert("1");
    toLoad = $(this).attr('href')+' #content';
    $('content-wrap1').load(toLoad);
}
Run Code Online (Sandbox Code Playgroud)

问题1:这是正确的用法on()吗?因为当我点击链接时,我没有进入alert 1屏幕,页面只是导航到whoweare.php

问题2:Incase我确实设法获得警报,是否可以通过点击链接来加载替换首先点击的链接的内容?

Tat*_*nit 7

问题1:这是on()的正确用法吗?因为当我点击链接时,我没有在屏幕上看到警报1,页面只是导航到whoweare.php

$(document).on("click", "#content a", function(){
        alert("1");
        toLoad = $(this).attr('href')+' #content';
        $('content-wrap1').load(toLoad);
})
Run Code Online (Sandbox Code Playgroud)

Ques2:柜面我设法得到警告,这可能theoritically点击加载,它取代了链接摆在首位点击内容的链接呢?

  • +1,好答案兄弟,请修复此选择器`#section1#content-wrap1 #content a`. (2认同)