【问题标题】:How does jQuery $(this) on Clicked element or class work? [duplicate]Clicked 元素或类上的 jQuery $(this) 是如何工作的? [复制]
【发布时间】:2021-08-16 00:49:44
【问题描述】:

我有一个简单的 html sn-p。

<div class="group">
    <div class="A1_B1 symptom">
        <ul><li><a href="#" class="hit">Click Symptom</li></ul>
    </div>
    <div class="A2_B2 remedy">
        <ul><li><a href="#" class="hit">Click Remedy</li></ul>
    </div>
</div>

现在点击操作...

$(document).on("click", ".hit", function (ev) {
if($(this).parents(".symptom"))
    alert("Symptom Clicked");
if($(this).parents(".remedy"))
    alert("Remedy Clicked");
});

$(this) 应该只引用我单击的元素。为什么即使 if 条件不满足,它也会同时提醒两个 alert 语句?

【问题讨论】:

  • parents 返回一个对象,对象是 JavaScript 中的真值。请改用parents(...).length

标签: jquery class if-statement click element


【解决方案1】:

如下修改你的代码

$(document).on("click", ".hit", function (ev) {
if($(this).parents(".symptom").length>0)
    alert("Symptom Clicked");
if($(this).parents(".remedy").length>0)
    alert("Remedy Clicked");
});

https://jsfiddle.net/1mz8s73b/

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-05-25
  • 2015-09-24
  • 2011-01-20
  • 2014-04-24
  • 2013-04-17
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多