javascript-检查元素是否存在于DOM中,如果不存在,则在每次输入单选后添加

前端之家收集整理的这篇文章主要介绍了javascript-检查元素是否存在于DOM中,如果不存在,则在每次输入单选后添加 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在更改表单上单选按钮的默认外观.为了做到这一点,我在jQuery输入标签之后添加了一个span标签.这对于在页面加载时呈现的单选按钮很好用.但是,表单使用条件语句来隐藏两个问题,因为在有条件显示它们之前它们不存在,所以两个问题不会在输入后添加跨度.表单具有一个js挂钩,当我有条件地添加新字段时,该挂钩会触发.我的问题是,如果用户有条件地揭示了两个问题,那么当我只需要将其添加一次时,就会将该跨度元素添加多次.

创建新的跨度标签后,我尝试检查要删除的跨度标签,但是我没有使其正常工作.我尝试将新创建的单选按钮保存在节点列表中并循环通过它们,但是最终添加了与节点列表长度一样多的span标签.

<!-- here is the html,the span is needed after the input tag -->
<div class="radio">
    <label>
        <input type="radio">
    </label>
</div>

// Adds the span to the hidden elements as they are revealed
$(document).on('cf.add',function() {

    if ($('.caldera-forms-conditional-field .radio input[type=radio] .radiomark').length == 0) {
        $(".caldera-forms-conditional-field .radio input[type=radio]").after("<span class='radiomark'></span>");
    }

});

它会根据需要添加范围,但是问题是当该js钩再次触发时,它会向每个单选按钮添加其他范围标签.如果用户更改了触发挂钩的单选按钮的答案,则会添加更多的跨度标签.有没有一种方法可以检查多个span标签删除重复的标签

最佳答案
您正在使用后代(选择器之间的空间)选择器.它查找属于或低于子元素的任何元素.而是将跨度放在同一父级中的输入之后.您想要的是相邻的兄弟选择器(),以防止在跨度已存在的情况下添加其他跨度.兄弟选择器查找与输入元素具有相同父元素并在输入元素之后的元素

例如.

<div class="radio"><!-- this is an element -->
    <label><!-- this is both a child and descendant of the div.radio element -->
        <input type="radio"><!-- this is a descendant of the div.radio element -->
    </label>
</div>

然而,

<div class="radio">
    <label>
        <input type="radio"> <!-- This is the element you are looking for -->
    </label>
</div>

脚本一次调用后,

<div class="radio">
    <label>
        <input type="radio">
        <span class="radiomark"></span><!-- This element gets added,it is a sibling of the input element -->
    </label>
</div>

因此,用于查找同级:

$(document).on('cf.add',function() {

    if ($('.caldera-forms-conditional-field .radio input[type=radio] + .radiomark').length == 0) {
        $(".caldera-forms-conditional-field .radio input[type=radio]").after("<span class='radiomark'></span>");
    }

});
原文链接:https://www.f2er.com/jquery/530861.html

猜你在找的jQuery相关文章