尝试使用其父元素也加载了ajax的ajax内容触发事件。
<div id="content"><!-- NOT ajax-loaded -->
<div id="location"> <!-- #location IS ajax-loaded -->
<div id="add_location> <!-- #add_location IS ajax-loaded from a #location event -->
<input type="text" id="add_location_city_example" />
<input type="text" id="add_location_state_example" />
<input type="submit" id="add_location_confirm" />
</div>
</div>
</div>
$(function(){
$('#content').on('click', '#add_location_confirm', function(){
console.log('debug 1');
add_location();
// will not be called
});
$('#location').on('click', '#add_location_confirm', function() {
console.log('debug 2');
// will not be called either
add_location();
});
});
如果我有onclick =“add_location()”和函数add_location(){console.log('debug 3);在我的.js然后它显然会被调用但是我不能得到$('#add_location_city_example')。val()因为它们都不在dom中。
注意:使用1.9.1
答案 0 :(得分:1)
我已经使用了一段时间了,这样可以更轻松地处理你所描述的情况+只有一个偶然的任务,几乎所有点击页面,包括将出现在页面上的元素未来:
$(document).bind('click', function (e) {
var target = $(e.target);
if (target.is('#content')) {
e.preventDefault();
// do whatever
} else if (target.is('#location')) {
e.preventDefault();
// do whatever else
}
});
或者在你的情况下它可能更像是这样:
$(document).bind('click', function (e) {
var target = $(e.target);
if (target.is('#add_location_confirm')) {
e.preventDefault();
if (target.closest('#location').length == 0) { // not yet have location injected via ajax
// do something
} else {
// location has been injected, do something else
}
});