jquery click对ajax生成的内容不起作用

时间:2012-02-18 21:37:06

标签: jquery ajax click live

我正在使用$(".button").on("click", function(){ });

单击容器上的按钮,然后完成ajax调用和内容 使用新内容进行更新,然后当我尝试点击.button它不会工作时...单击按钮时不会返回任何内容。

我甚至尝试过

$(".button").live("click", function(){ });

$(".button").click(function(){ });

我怎样才能让它发挥作用?

编辑: 我的HTML:

<div class="container">
   <ul>
       <li>item1</li>
       <li>item2</li>
       <li>item3</li>
   </ul>
   <input type="button" value="reload" class="button" />
</div>

4 个答案:

答案 0 :(得分:141)

应该这样做。

$('body').on('click', '.button', function (){
        alert('click!');
    });

如果您的容器在ajax请求期间没有更改,则性能更高:

$('.container').on('click', '.button', function (){
        alert('click!');
    });

始终将委托事件绑定到最接近的包含动态元素的静态元素。

答案 1 :(得分:39)

好的,我正确使用.on()函数解决了我的问题,因为我错过了一个参数。

而不是

$(".button").on("click", function() { } );

我用过

$(".container").on("click", ".button", function() { } );

答案 2 :(得分:8)

而不是:

$(".button").on("click", function() { } );

我用过:

$(".container").on("click", ".button", function() { } );

我已经使用了它并且它有效。

答案 3 :(得分:3)

这是你想要做的吗?请注意,我将$.on()放在父级上,但为操作选择.button

  

.on(事件 [,选择器] [,数据],处理程序(eventObject))

     

selector 用于过滤所选内容的后代的选择器字符串   触发事件的元素。如果选择器为null或省略,   事件总是在到达所选元素时被触发。

http://api.jquery.com/on/

<div id="stuff">
    <button class="button">Click me!</button>
    <p>Stuff</p>
</div>

var $stuff = $('#stuff'),
    ajaxContent = $stuff.html();

$stuff.on('click', '.button', function(){
    $.get('/echo/html/', function(){
        $stuff.empty();
        console.log($stuff.html());
        alert($stuff.html()); // Look behind, #stuff is empty.
        $stuff.html(ajaxContent);
        console.log($stuff.html());
    });
});

http://jsfiddle.net/62uSU/1

另一个示范:

var $stuff = $('#stuff'),
    ajaxContent = $stuff.html(),
    $ajaxContent,
    colors = ['blue','green','red'],
    color = 0;

$stuff.on('click', '.button', function(){
    $.get('/echo/html/', function(){
        color++;
        if (color == colors.length) color = 0;
        console.log($stuff.html());
        alert($stuff.html());
        $ajaxContent = $(ajaxContent);
        $stuff.append($ajaxContent).css('color', colors[color]);
        console.log($stuff.html());
    });
});

http://jsfiddle.net/62uSU/2/

相关问题