我有一个选择下拉列表,每个选项都在下拉列表下面显示一个唯一的字符串。
这个字符串位于类为dropdown_text
的div中。
如果下拉列表下面的文本包含某个单词(即"textstring"(,我想在包含下拉列表的父元素中添加一个类。
父元素是一个类为wrap
的div。
到目前为止,我已经能够将类添加到父元素中,但当下拉列表下的文本不包含单词"textstring"时,我在删除类时遇到了问题。
到目前为止,这是我的jquery;
jQuery(document).ready(function($) {
$(document).on('change', '#product', function(){
var userString = 'textstring';
$('div.dropdown_text:contains('+ userString +')').closest('.wrap').addClass('new-class');
$('div.dropdown_text:not(:contains ('+ userString +'))').closest('.wrap').removeClass('new-class');
});
});
下面是一些标记示例;
<div class="wrap">
<select id="product">
<option>generictext</option>
<option>textstring</option>
<option>generictextagain</option>
</select>
<div class="dropdown_text">
<p>generictext</p><!--This text changes depending on which select option from above is selected-->
</div>
</div>
网站中的实际标记比这复杂得多,因此在jQuery中使用了.closest
。.closest
需要保持原位。
在jQuery函数的下面一行中,我做错了什么?当下拉列表下方未显示"textstring"时,不会从父级中删除该类。
$('div.dropdown_text:not(:contains ('+ userString +'))').closest('.wrap').removeClass('new-class');
任何帮助都将不胜感激。
更新:我使用的是jQuery版本1.12.4。jQuery的那一行中是否有1.12.4版本不支持的内容?
我通过删除:contains
和userString
之后的空格解决了这个问题,如下所示;
$('div.dropdown_text:not(:contains('+userString+'))').closest('.wrap').removeClass('new-class');