我有一个列表,其中包含x列数据。当单击行中的编辑按钮时,我希望将此行中每一列的html内容设置为一个数组,该数组的键由列名称属性值命名。
data['id'] = '123';
data['name'] = 'John Doe';
data['city'] = 'Arlington';为此,我在edit div上启动了一个click事件。在这个函数中,我使用$( this )选择器在所有具有name属性的元素上设置each()循环。在这个循环中,我再次使用$( this )选择器捕获每个匹配元素的名称和值。
所以,我的问题是:尽管它可以工作--它可以这样做吗?在同一个函数中对两个不同的东西使用$(this)?有没有别的办法?
以下是我的工作示例代码
$( document ).ready(function() {
$(document).on( "click", ".edit", function() {
var data = {};
$(this).closest('.row').children('div[name]').each(function() {
//form_data.append($(this).attr('name'), $(this).html());
data[$(this).attr('name')] = $(this).html();
});
$('#result').html(JSON.stringify(data, null, 4));
});
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div name="id">123</div>
<div name="name">John Doe</div>
<div name="city">Berlin</div>
<div class="edit">> edit <</div>
</div>
<br clear="all">
<div id="result"></div>
发布于 2019-01-08 20:23:33
允许吗?
它是有效的,所以当然。
这取决于你所说的“允许”是什么意思。
(有很多关于这个的问题,或者由这个引起的问题,可以确认它会导致问题)。
重用变量名(在本例中为‘this’)是很常见的,并且基于作用域。
很难判断您是否有bug,因为您实际上需要的是".edit“html或".edit”属性,而不是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 (或者您会吗?我不知道您的要求...)。所以“不太可能”
但是很容易看出,在另一个场景中,您希望引用在嵌套.each中单击的btn==this。
发布于 2019-01-08 20:11:49
试试这个小把戏:
$( document ).ready(function() {
$(document).on( "click", ".edit", function() {
var data = {};
var that = this; // trick here
$(this).closest('.row').children('div[name]').each(function() {
//form_data.append($(this).attr('name'), $(this).html());
data[$(this).attr('name')] = $(that).html();// replace this = that if you want to get parent element
});
$('#result').html(JSON.stringify(data, null, 4));
});
});发布于 2019-01-08 20:16:16
没有什么问题,你要做的就是
function setDivs() {
//form_data.append($(this).attr('name'), $(this).html());
data[$(this).attr('name')] = $(this).html();
}
function docClick(){
var data = {};
$(this).closest('.row').children('div[name]').each(setDivs);
$('#result').html(JSON.stringify(data, null, 4));
}
function docReady(){
$(document).on( "click", ".edit", docClick)
}
$( document ).ready(docReady);<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div name="id">123</div>
<div name="name">John Doe</div>
<div name="city">Berlin</div>
<div class="edit">> edit <</div>
</div>
<br clear="all">
<div id="result"></div>
https://stackoverflow.com/questions/54091512
复制相似问题