javascript - 如何将类添加到相邻元素的输入元素?

标签 javascript jquery html

($(this).addClass("error")

添加类错误以在验证时选择。 但与此同时,我还想将此类添加到 next <span> 中的输入字段中. 这是为了解决我所说的问题 here .我认为可以这样做。

以下是我要添加 class="error" 的 html

<select data-placeholder="Pick the ones that apply to you" multiple="" class="js-selection select2-hidden-accessible error" name="option" data-placement="left" data-toggle="tooltip" data-required="true" tabindex="-1" aria-hidden="true" placeholder="Please fill out this field">
                        <option selected="" value=""></option>
                        <option value="1">Shipping / post</option>
                        <option value="2">Customers can collect</option>
                        <option value="3">Other</option>
</select>

<span class="select2 select2-container select2-container--default" dir="ltr" style="width: auto;">
 <span class="selection">
   <span aria-expanded="false" aria-haspopup="true" aria-autocomplete="list" role="combobox" class="select2-selection select2-selection--multiple" tabindex="0">
     <ul class="select2-selection__rendered">
       <li class="select2-search select2-search--inline">
          <input type="search" role="textbox" spellcheck="false" autocapitalize="off" autocorrect="off" autocomplete="off" tabindex="-1" class="select2-search__field" placeholder="Pick the ones that apply to you" style="width: 0px;">
       </li>
     </ul>
    </span>
 </span>
<span aria-hidden="true" class="dropdown-wrapper"></span></span>

最佳答案

根据你的解释thisselect,所以你可以这样做:

$(this).addClass('error');
$(this).next().find('input').addClass('error');

您也可以使用 add() 将它们组合成一个操作:

$(this).add($(this).next().find('input')).addClass('error');

关于javascript - 如何将类添加到相邻元素的输入元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30082359/

相关文章:

javascript - 使用 mootools 多次替换元素名称

jquery - 切换表行同级

javascript - Python 与 JavaScript 交互?

html - div 与 css 背景的水平对齐

javascript - 将参数传递给解析函数

javascript - 遍历文本框插入不在数组中的值文本框

javascript - 如何在内部调用快速导出方法?

jquery - 帮助自定义我自己的工具提示 Angular 并改善定位

html - 修复 IE11 的图像缩放错误?

javascript - 使用 Javascript/jQuery 创建摘录