jQuery无法正常工作 [英] jquery on not working properly

查看:84
本文介绍了jQuery无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下jquery代码

I have the following jquery code

$(".delete").on('click', function (e){
    e.preventDefault();
    var id = $(this).prop('id');
    console.log('Delete button id: '+id);
    var formWrapper = $(".form-wrapper:nth-child("+id+")");
    console.log(formWrapper);
    formWrapper.remove();
});

delete .delete位于表单内的按钮上

the delete .delete is on a button inside a form

<button class="btn btn-danger delete">-<button>

,并且在页面加载后,按钮会动态加载到页面上.因此,我使用了on函数来附加click事件.但这是行不通的,并且永远不会调用该函数.不仅应该不仅适用于加载期间页面上的元素,而且还适用于事后加载的元素?

and the button is loaded on the paged ynamically after the page has loaded. So I used the on function to attach the click event on it. But it won't work and the function is never called. Isn't on supposed to work not only for elements that are on the page during load but for those that get loaded afterwards?

推荐答案

您是说特定按钮正在动态加载到DOM,因此在这种情况下,您必须使用

You are saying that the particular button is getting loaded to the DOM dynamically, so in this context you have to use event-delegation to make your code working.

通常,您的代码会在DOM加载后立即为类.delete注册该元素的事件.实际上,那时我们没有任何具有该标识的元素,因此该上下文是event-delegation的选择.

Normally your code will register event for the element with the class .delete immediately after the DOM loaded. Actually we dont have any elements with that identity at that time, So this context is opt for event-delegation.

我实际上不知道您的确切dom结构,因此我已经使用文档委托了click事件,但是您应该更喜欢该元素的一些静态父级来实现它,

I actually dont know the exact dom structure of yours, so that i have used document to delegate the click event, But you should prefer some static parent of that element to implement it,

尝试

$(document).on("click",".delete", function (e){

这篇关于jQuery无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆