允许吗?
当然,这很管用。
取决于你所说的“允许”是什么意思。
(有很多关于这个的问题或者由这个引起的问题证实了它引起了问题)。
重用变量名(在本例中为“this”)是常见的,并且基于
范围
.
很难判断您是否有bug,因为您实际上需要“.edit”html或“.edit”attr,而不是
div
所以你可以通过复制来消除混乱
this
对于变量:
$(document).on( "click", ".edit", function() {
var data = {};
var btn = $(this); // the button that was clicked
btn.closest('.row').children('div[name]').each(function() {
// Do you mean the div or did you really mean the clicked button?
data[$(this).attr('name')] = $(this).html();
var div = $(this); // the child div
// clearly not what is desired
// `btn` variable referring to the outer `this`
data[div.attr('name')] = btn.html();
// intention clear
data[div.attr('name')] = div.html();
});
$('#result').html(JSON.stringify(data, null, 4));
});
在本例中,它是“清晰的”,因为您不会在所有数据条目上使用btn html(或者您会这样做吗?我不知道你的要求……。所以“不太可能”。
但是,很容易看出,在另一种情况下,你会如何引用被点击的内容。
btn==this
在嵌套的内部
.each
.