我有这个 HTML 代码
<div class="col-sm-12 col-xs-12 col-md-12 no-padding">
<button class="accordion active_alarms_modification_div" id="<?=$alarm->id?>" value="<?=$alarm->id?>">Keywords: "<?php echo $alarm->original_keywords ?>" - Activated on: <?=$alarm->creation_date?> </button>
<div class="panel table-responsive">
<div class="col-sm-12 col-xs-12 col-md-12 kp">
<form>
<div class="col-sm-12 col-xs-12 col-md-12 nor-inputs no-padding">
我无法检索 id 和 value 的值,因为结果是“未定义”。"this" 或 "$(this)" 元素似乎在同一函数中被正确评估,因为使用它执行其他操作。这里的代码
$('.active_alarms_modification_div').each(function(i, obj) {
$(this).on("click", function(evt) {
setTimeout(function(){
/* Toggle between adding and removing the "active" class,
to highlight the button that controls the panel */
$(this).toggleClass('active'); // this is recognised, it properly refers to that div
console.log("chart button id\n");
console.log($(this).attr('value')); // this result undefined
console.log(this.value); // this result undefined
console.log($(this).attr('id')); // this result undefined
console.log(this.id); // this result undefined
/* Toggle between hiding and showing the active panel */
var panel = $(this).next(); // this is recognised, it properly refers to the next inner div of active_alarms_modification_div
if (panel.css("display") === "block") {
panel.css('display', 'none');
} else {
panel.css('display', 'block');
//window.charts[this.id].render();
}
}, 100);
});
});
任何想法?
更新:解决方案 问题是注释中突出显示的问题,即超时管理中的“this”指的是“window”对象,而不是“active_alarms_modification_div”类标识的容器div。我在这里复制修复解决方案,以防有人在阅读我的问题时发现同样的问题,而不是我问题本身顶部指示的问题。
$('.active_alarms_modification_div').each(function(i, obj) {
var div = this; // reference to the container div
$(this).on("click", function(evt) {
setTimeout(function(){ // warning: in here (timeout) "this" referes to wiindow, not to the container div
/* Toggle between adding and removing the "active" class,
to highlight the button that controls the panel */
$(div).toggleClass('active');
/* Toggle between hiding and showing the active panel */
//var panel = $(this).next(); // this is recognised, it properly refers to the next inner div of active_alarms_modification_div
var panel = $(div).next();
if (panel.css("display") === "block") {
panel.css('display', 'none');
} else {
panel.css('display', 'block');
window.charts[div.id].render();
}
}, 100);
});
});