【问题标题】:Select Single DOM Element选择单个 DOM 元素
【发布时间】:2018-05-25 19:35:42
【问题描述】:

我有一个事件监听器,它正在寻找点击某个类的 DOM 元素,然后更改 innerHTML。它可以工作,除了它会更改具有相同类的所有元素的innerHTML,而不仅仅是单击的那个。有没有办法将范围限制为被点击的元素,还是我需要给所有元素自己的 ID 并根据 ID 调用它们?

这是我正在使用的功能:

$("button.accordion").click(function(){
    if ($(".caretUD").html("▼")) {
            $(".caretUD").html("▲");
    } else {
        console.log("I'm not working...");
    }
});

【问题讨论】:

  • 请与我们分享您的 HTML。按钮与插入符号有何关系?
  • @KevinB 我误读了这个问题,我的错。
  • @Luca 我误读了这个问题,我的错。
  • @Mikey 我误读了这个问题,我的错。
  • @ScottMarcus 不用担心。这个问题一开始就不清楚。

标签: javascript jquery html


【解决方案1】:

这有帮助吗? 这是当前点击的元素。

请注意,event.currentTarget 是记录事件的元素,也是触发事件的元素(可以是 event.currentTarget 的子元素或它本身)。在你的情况下,有一个按钮,它应该是一样的。

$("button.accordion").click(function(event) {
    if ($(this).html("▼")) {
        $(this).html("▲");
    } else {
        console.log("I'm not working...");
    }
});

【讨论】:

  • 这也不会更改 OP 想要更改其 HTML 的 .caretUD 元素的 HTML。
  • 他想改变点击的元素“而不仅仅是点击的那个”。
  • 我认为您的答案是最接近的,因为您限制了范围。我认为应该是$('.caretUD', this).html('▲')$(this).find('.caretUD').html('▲')。虽然 OP 的 IF 条件没有意义。
  • 这取决于需要。如果按钮有类 caretUD,这将不起作用。我更喜欢让 OP 选择他想要的。
【解决方案2】:

如果.caretUDbutton.accordian 都包含在同一个容器元素中,你想要的是:

$("button.accordion").click(function() {
    var caret = $(this).closest(".container").find(".caretUD");
    if (caret.html() == "&#9660") {
        caret.html("▲");
    } else {
        console.log("I'm not working");
    }
});

.container 替换为包含按钮和相应插入符号的元素的实际类。

【讨论】:

    【解决方案3】:
    var els = document.getElementsByClassName("button.accordion"); // get all the elements with a certain class
        for (var i = 0; i < els.length; i++){
            els[i].addEventListener('click',function(e){
                e.target.innerHTML = "something"; // e attribute is the key in this solution, as it gets the single DOM element that fired the event
            });
        }
    

    jQuery解决方案:

    $("button.accordion").click(function(){
        if ($(this).html() == "&#9660;") {
                $(this).html("&#9650;");
        } else {
            console.log("I'm not working...");
        }
    }); 
    

    【讨论】:

    • 我的解决方案对我很有效,不知道你为什么不赞成它:)
    • ...什么?这与您之前的答案相同,但没有 jQuery
    • 这正是他想要的:改变唯一被点击的元素的innerHTML..
    • “有没有办法将范围限制为被点击的元素,还是我需要给所有元素自己的 ID 并根据 ID 调用它们?”他从未提到他想要一个 jQuery 解决方案。
    • 仅发布代码是一个低质量的答案,并且会在提供对您正在做什么和原因的解释之前获得反对票。此外,这个问题被标记为 jQuery,所以他可能想继续使用他选择的平台。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2014-09-23
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2019-02-27
    • 2019-12-21
    相关资源
    最近更新 更多