不能用Jquery从$.get() / $.load()函数中选择ID.请帮帮我
Cannot select ID with Jquery from $.get() / $.load() function. Please Help Me?
我的Javascript是这样的
$('button').click(function(){
//load the data and place inside to #content
});
$('#id-from-data-that-load').click(function(){
//Do some action
});
这是html标签
<button>Load</button>
<div id="content">
//Empty Data
</div>
当button LOAD被点击时,html将是这样的
<button>Load</button>
<div id="content">
<div id="id-from-data-that-load">
content that load
</div>
</div>
但是,当我点击div id-from-data-load时,函数不会运行。
如何解决?
您需要为div事件使用live。应该是这样的:
$('#id-from-data-that-load').live("click", function(){
//Do some action
});
或者你也可以这样做:
var submitted = false;
$('button').click(function(){
// If the button was clicked before, we don't submit again.
if (submitted == true) { return false; }
// Set submitted to true, so when user clicks the button again,
// this operation will not be processed one more time.
submitted = true;
//load the data and place inside to #content
$.post("/getdata", {}, function(response) {
//after the load happened we will insert the data into the div.
$("#content").html(response);
// Do the bindings here.
$('#id-from-data-that-load').click(function(){
//Do some action
});
});
return false;
});
try:
$('#id-from-data-that-load').live("click", function() {
alert($(this).attr("id");
});
您需要将事件绑定到运行时通过.live
处理程序或.delegate
处理程序加载的元素。这是因为当您将事件绑定到元素时,它们并不存在于dom中。live和delegate能帮你实现这个。参见@shree的答案
在内容中加载数据后绑定id-from-data-that-load。
$('button').click(function(){
//load the data and place inside to #content
$('#id-from-data-that-load').click(function(){
//Do some action
});
});
绑定li时,可以将函数名硬编码到onclick属性中。
<li onclick="myFunction">Blah Blah Blah</li>
相关文章:
- 在jquery中选择id以字符串开头的元素
- 使用regex选择ID元素
- Bootstrap Navbar在选择ID元素后未折叠
- 选择id中带有双点的元素,错误:“#octo:cat”不是有效的选择器
- jQuery 选择 # id 以 word 作为前缀,计数器作为后缀
- 在数据响应中选择 #id.html
- 如何根据“选择 ID”选项值更改表的行和列
- 从变量中选择id
- jQuery从逗号分隔的列表中选择ID
- 选择ID为另一个元素中属性的元素
- 在jquery中选择ID+任意数字
- 动态添加行表需要更改选择 id 标签
- 根据其父ID选择ID
- 选择ID中有句号的元素
- 根据标签选择id
- 在Javascript中使用循环选择id的数量
- 没有选择ID
- Javascript -在选择id时遇到麻烦
- 不能用Jquery从$.get() / $.load()函数中选择ID.请帮帮我
- 用于从表中选择ID的JavaScript