javascript - 是否允许在函数和包含的每个循环中使用 jQuery $(this) 选择器两次?
问题描述
我有一个列表,其中包含 x 列数据。当点击一行中的一个编辑按钮时,我想将这一行的每一列的html内容设置成一个数组,其中有一个name属性,其中key由columns name属性值命名。
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>
解决方案
是否允许?
它当然有效。
取决于您所说的“允许”是什么意思。
- 是否令人困惑-也许。
- 它会引起问题吗?肯定会。
(有很多关于这个的问题或由此引起的问题,确认它会导致问题)。
重用变量名(在这种情况下为“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(或者您会吗?我不知道您的要求......)。所以“不太可能”。
但是很容易看出,在另一种情况下,您希望引用btn==this
嵌套的.each
.
推荐阅读
- reactjs - setupTests.js 未在 CRA 反应应用程序中自动加载
- ios - 如何在Swift中的BezierPath之后为imageView的点1到2和点2到3设置不同的animation.duration时间?
- amazon-web-services - 如何在我的反应原生应用程序中覆盖 AmplifyTheme
- jenkins-pipeline - Jenkins 管道在 UI 中工作,但不适用于 SCM
- elasticsearch - 带有过滤条件和字符串搜索的 Elasticsearch bool 查询返回不一致的结果
- presto - 在 Presto 中添加两个地图
- tooltip - Amcharts 4,xychart,限制工具提示的数量并将信息组合在一个工具提示中
- html - 防止所选文本行之间出现空白
- javascript - 是否可以在没有“允许脚本”标志的情况下将 postMessage 发送到沙盒 iframe?
- javascript - 从 javascript 到 python 的数据(使用 post)