gpt4 book ai didi

jquery - 单击事件在元素内的斜体文本上失败

转载 作者:行者123 更新时间:2023-12-01 07:04:03 25 4
gpt4 key购买 nike

我有一个附加到元素 searchresults 的生成列表。单击列表中的成员会返回关联的 ID,但如果单击的区域位于斜体标记内,则不会返回。

生成的列表如下所示:

<div id="searchresults">;
<p id="oppnum248">Some text here (<i>And more here</i>)</p>
<p id="oppnum786">Some other text here (<i>And here</i>)</p>
...
</div>

这是 jQuery 代码的片段:

$('#searchresults').on('click', '[id^=oppnum]', function(event) {
var oppID = event.target.id.slice(6);
...
});

单击任何斜体字都会触发处理程序,但 oppID 是一个空字符串。删除斜体标签后,处理程序将返回整个文本的 ID。

在线搜索没有找到任何相关内容。我应该如何修改我的代码?

$('#searchresults').on('click', '[id^=oppnum]', function(event) {
var oppID = event.target.id.slice(6);
alert(oppID);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="searchresults">;
<p id="oppnum248">Some text here (And more here)</p>
<p id="oppnum786">Some other text here (<i>And here</i>)</p>
</div>

最佳答案

问题是因为 event.target 将是被单击的元素;在这种情况下,要么是i,要么是p。如果是前者,则它没有 id 属性,因此返回空字符串。

要解决此问题,请在事件处理程序中使用 this 关键字,因为它始终引用事件处理程序绑定(bind)到的元素,即使子元素实际引发了事件也是如此。试试这个:

$('#searchresults').on('click', '[id^=oppnum]', function() {
var oppID = this.id.slice(6);
console.log(oppID);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="searchresults">
<p id="oppnum248">Some text here (<i>And more here</i>)</p>
<p id="oppnum786">Some other text here (<i>And here</i>)</p>
</div>

关于jquery - 单击事件在元素内的斜体文本上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58450963/

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