gpt4 book ai didi

javascript - 是否允许在函数和包含的每个循环中两次使用 jQuery $(this) 选择器?

转载 作者:行者123 更新时间:2023-11-30 11:09:59 25 4
gpt4 key购买 nike

我有一个列表,其中包含 x 列数据。当点击一行中的编辑按钮时,我想将这一行每一列的html内容设置为一个数组,其中的键由列名称属性值命名。

data['id']   = '123';
data['name'] = 'John Doe';
data['city'] = 'Arlington';

为此,我在编辑 div 上启动了一个点击事件。在这个函数中,我正在使用 $(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>

最佳答案

Is it allowed?

当然可以。

取决于您所说的“允许”是什么意思。

  • 是否令人困惑 - 也许吧。
  • 它会导致问题吗?肯定会。

(有很多关于 SO 的问题或由此引起的问题,确认它会导致问题)。

重用变量名(在本例中为“this”)很常见,并且基于作用域

很难判断您是否有错误,因为您实际上想要“.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(或者您会吗?我不知道您的要求...)。所以“不太可能”。

但很容易看出,在另一种情况下,您可能希望在嵌套的 .each 中引用单击的内容 btn==this

关于javascript - 是否允许在函数和包含的每个循环中两次使用 jQuery $(this) 选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54091512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com