【问题标题】:Jquery method not working for button after html appended using ajax使用ajax附加html后,Jquery方法不适用于按钮
【发布时间】:2014-04-23 12:34:04
【问题描述】:

我用一些html和javascript加载了一个html页面,代码如下

<button id="test"> test button </button>
<div id="result"></div>

我的脚本如下(jquery 已正确添加)

<script>
$("#test").on("click" , function(){
    $("#result").text("hello world");
});
$("#button1").on("click" , function(){
        $("#result").text("goodbye world");
    });
</script>

测试按钮工作正常。现在让我们说而不是你好世界 被打印出来,我们在结果 div 中附加了一个添加的按钮 已设置的方法。

<button id="test"> test button </button>
    <div id="result"><button id="button1">Button 1</button></div>

点击button1时什么都没有发生?为什么会这样?我认为它没有注册 html,因为它是动态创建的。我怎样才能使它在单击此按钮时发生某些事情?提前谢谢你

【问题讨论】:

  • 添加按钮的方法在哪里?

标签: javascript jquery html ajax


【解决方案1】:

这个按钮在页面上是动态出现的,所以你需要像这样编写它的事件:

$('#result').on("click","#button1" , function(){
            $("#result").text("goodbye world");
        });

或:

$(document).on("click","#button1" , function(){
        $("#result").text("goodbye world");
    });

阅读更多HERE

【讨论】:

  • 您需要按照建议进行事件委托,learn.jquery.com/events/event-delegation
  • 如果有更好的选择,请不要使用document作为委托目标。
  • @jack 该元素在 doam 加载后动态出现,有什么替代方法而不是这个??
  • 杰克有什么更好的选择?身体元素?
  • 是的,你做对了..当 html 在加载 dom 后在页面上呈现时,我们需要使用委托绑定事件,我就是这样做的
【解决方案2】:

使用此代码

 $(document).ready(function () {
        $("#test").click(function () {
            $("#result").text("Hello");
        });
        $("#button1").click(function () {
            alert('');
            $("#result").text("hello world");
        });
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 2017-09-16
    • 2013-05-08
    相关资源
    最近更新 更多