很难知道 event.data.x
方法发生了什么。
你能告诉我这段代码下面的 event.data.x 到底指的是什么吗?
除此function(event)
部分外,我主要了解代码的工作原理,例如函数结构、参数、方法。
是参数名为event
的函数个数吗?
如果你能用简单的词来解释那些就太好了。
加:在Jquery中索引和数据有区别吗??
$(document).ready(function() {
$("p").each(function(i) {
$(this).on("click", {
x: i
}, function(event) {
alert("The " + $(this).index() + ". paragraph has data: " + event.data.x);
});
});
});
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>This is another paragraph.</p>
<script src="http://code.jquery.com/jquery-3.3.1.js"></script>
最佳答案
$(this).index()
返回您在其容器元素中单击的元素的索引。
event.data.x
包含 i
的值来自 .each()
与事件监听器附加到的元素对应的循环。
在此示例中,它们是相同的,因为 <p>
元素是容器的唯一子元素。但是,如果稍微修改一下示例,您就会看到不同之处。
$(document).ready(function() {
$("p").each(function(i) {
$(this).on("click", {
x: i
}, function(event) {
alert("The " + $(this).index() + ". paragraph has data: " + event.data.x);
});
});
});
<p>This is a paragraph.</p>
<div>This is a div</div>
<p>This is another paragraph.</p>
<p>This is another paragraph.</p>
<div>
<p>This is a paragraph nested deeper</p>
</div>
<script src="http://code.jquery.com/jquery-3.3.1.js"></script>
第一个 DIV 是容器的另一个子元素,因此它会影响其后段落的索引。最后一段在不同的容器中,因此索引从 0
开始那里。
但在所有情况下,变量 i
只是按顺序递增,这保存在 event.data.x
中.
关于javascript - JavaScript 中索引和数据的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52673383/