Jquery - 从使用函数创建的按钮调用函数 [英] Jquery - Calling a Function from a button created with a function

查看:273
本文介绍了Jquery - 从使用函数创建的按钮调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这在Jquery中有效:

 < input type =buttonclass =govalue =GO /> 

$(。go)。click(function(){
$(#test)。html(TEST TEST TEST);
});

但是如果我尝试从使用下面创建的按钮访问go函数失败。 p>

  $(。new)。click(function(){
$ .ajax({
url :$(this).attr(data-value),
success:function(data,textStatus,xhr){
$('#DIV')。html('< input type = buttonclass =govalue =go/>');
}
}
});
}

此代码在另一个函数点击函数完成时使用。



任何原因?



感谢

解决方案

事件处理程序仅绑定到当前选定的元素;它们必须在您的代码进行事件绑定调用时在页面上存在。



委派的事件的优点是它们可以处理来自后代元素的事件,



您需要使用 事件委派 。您必须使用委托事件方法 .on() 。 / p>

ie

  $(document).on('event' 'selector',callback_function)

理想情况下应该替换 document 与最接近的静态容器。



示例

  $('#DIV')。on 'click','.go',function(){
// Your Code
});


this works in Jquery :

<input type="button" class="go" value="GO" />

$(".go").click(function() {
$("#test").html("TEST TEST TEST");
});

But if I try to access the go function from a button created using the following it fails.

$(".new").click(function() {
$.ajax({
        url: $(this).attr("data-value"),
        success: function(data, textStatus, xhr) {
        $('#DIV').html('<input type="button" class="go" value="go" />');
    }
}
 });
});

This code is used when another function click function completes.

Any reason why ?

Thanks

解决方案

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

As you are creating button dynamically.

You need to use Event Delegation. You have to use .on() using delegated-events approach.

i.e.

$(document).on('event','selector',callback_function)

Ideally you should replace document with closest static container.

Example

$('#DIV').on('click', '.go', function () {
    //Your Code     
});

这篇关于Jquery - 从使用函数创建的按钮调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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