Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

jquery - 事件触发后,ajax调用后创建的按钮不起作用[重复](Button created after ajax call not working while event is triggered [duplicate])

I have the following code in html:

(我在html中有以下代码:)

<table class="table table-striped">
<thead class="inner">
    <tr>
        <th>Name</th>
        <th>Parent</th>
        <th>Priority</th>
        <th>Action</th>
    </tr>
</thead>
<tbody id="check">
    <tr>
        <td><a href="">test</a></td>
        <td>null</td>
        <td>0</td>
        <td>
            <button value="3" type="button" class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
        </td>
    </tr>
    <tr>
        <td><a href="">Lifestyle</a></td>
        <td>null</td>
        <td>1</td>
        <td>
            <button value="2" type="button" class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
        </td>
    </tr>
    <tr>
        <td><a href="">Travel</a></td>
        <td>null</td>
        <td>1</td>
        <td>
            <button value="1" type="button" class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button>
        </td>
    </tr>
</tbody>

And I have the following code in the footer:

(在页脚中有以下代码:)

$("#check tr td button").click(function () {
    alert('here');
});

But the event does not seems to work.

(但是该事件似乎不起作用。)

Why is my code not working?

(为什么我的代码不起作用?)

The data in table are created after a ajax call.

(表中的数据是在ajax调用之后创建的。)

Is it because of ajax?

(是因为Ajax吗?)

  ask by Alisha translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The event is registered before the elements exist in the DOM , which is why the function is not triggered.

(在元素存在于DOM之前注册该事件,这就是为什么不触发该功能的原因。)

The solution is to define the code after your ajax or use event delegation as below

(解决方案是在ajax之后定义代码或使用事件委托,如下所示)

$(document).ready(function() {
  $(document).on("click", "#check tr td button", function() {
    alert('here');
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...