[英]Unable to select div (generated dynamically) using jQuery
I have a popup box that retrieves content data via AJAX and displays this content. 我有一个弹出框,通过AJAX检索内容数据并显示此内容。 This is taken care of by the asynchronous function generateInfoboxContent()
and the HTML content retrieved is boxText
. 这由异步函数generateInfoboxContent()
并且检索的HTML内容是boxText
。 The content that will be displayed depends on the item that was clicked by the user. 将显示的内容取决于用户单击的项目。 infoboxes[i].setContent
and infoboxes[i].open()
are functions that add the content to the HTML page. infoboxes[i].setContent
和infoboxes[i].setContent
infoboxes[i].open()
是将内容添加到HTML页面的函数。
Problem: I want to select a div infobox_header_favorite
within this dynamically generated content boxText
using jQuery using .click()
but the click handler does not seem to be triggered! 问题:我想在这个动态生成的内容boxText
使用jQuery使用boxText
.click()
选择div infobox_header_favorite
,但点击处理程序似乎没有被触发! How can I solve his problem? 我该如何解决他的问题?
jQuery Code jQuery代码
(function(i) {
var boxText = generateInfoboxContent(infoboxes[i].listing_id, function(boxText) {
infoboxes[i].setContent(boxText);
infoboxes[i].open(map, markers[i]);
infoboxes[i].show();
infoboxes_open.push(infoboxes[i]);
console.log('Hello');
// Favorite function
$("#infobox_header_favorite").click(function() {
console.log('favorite!');
toggleFavorite(infoboxes[i].listing_id);
});
});
})(i);
Result 结果
Hello
is written to the console, but favorite!
Hello
写到控制台,但favorite!
is not written to the console log when the div infobox_header_favorite
is clicked. 单击div infobox_header_favorite
时,不会将其写入控制台日志。
UPDATE UPDATE
jQuery Code jQuery代码
$.getJSON(base_url + 'index.php/main/getplaces',
{ data: data },
function(json){
for( i = 0; i < json.length; i++) {
(function(i) {
var boxText = generateInfoboxContent(infoboxes[i].listing_id, function(boxText) {
infoboxes[i].setContent(boxText);
infoboxes[i].open(map, markers[i]);
infoboxes[i].show();
infoboxes_open.push(infoboxes[i]);
console.log('Hello');
// Favorite function
$("#infobox_header_favorite").click(function() {
console.log('favorite!');
toggleFavorite(infoboxes[i].listing_id);
});
});
})(i);
}
});
UPDATE 2 更新2
for( i = 0; i < json.length; i++) {
(function(i) {
var boxText = generateInfoboxContent(infoboxes[i].listing_id, function(boxText) {
infoboxes[i].setContent(boxText);
infoboxes[i].open(map, markers[i]);
infoboxes[i].show();
infoboxes_open.push(infoboxes[i]);
console.log('Hello');
// Favorite function
$("#infobox_header_favorite").on("click", function() {
console.log('asd');
toggleFavorite(infoboxes[i].listing_id);
});
});
})(i);
}
Received an error Uncaught TypeError: Object [object Object] has no method 'on'
收到错误Uncaught TypeError: Object [object Object] has no method 'on'
Use .live()
or .on()
to bind event to dynamically added elements. 使用.live()
或.on()
将事件绑定到动态添加的元素。
.live()
is deprecated in jQuery 1.7 .live()
在jQuery 1.7中已弃用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.