我正在尝试根据元框(下拉列表)的值在 wp post 上显示不同的内容。因此,如果我有“视频”、“代码”和“图像”作为下拉列表中的选项,我会制作一个隐藏的 div,根据所选内容显示“视频”、“代码”或“图像”。然后我需要 jQuery(或 Javascript)来查看以太字的隐藏 div,并显示/隐藏一些 div。
这是我到目前为止的一些代码。
if (jQuery("div.type:contains('Video')")) {
jQuery(".Code").hide();
jQuery(".Image").hide();
}
但我需要的是隐藏除正确的 div 之外的所有 div。
示例
HTML
<div class="type">video</div>
<div class="Video">Video Here</div>
<div class="Code">Code Here</div>
<div class="Image">Image Here</div>
jQuery
if (jQuery("div.type:contains('video')")) {
jQuery(".Video").show();
jQuery(".Code").hide();
jQuery(".Image").hide();
}
if (jQuery("div.type:contains('code')")) {
jQuery(".Video").hide();
jQuery(".Code").show();
jQuery(".Image").hide();
}
if (jQuery("div.type:contains('image')")) {
jQuery(".Video").hide();
jQuery(".Code").hide();
jQuery(".Image").show();
}
为什么这不起作用?
看看 jsfiddle 输入的内容 <div class="type">
它会显示<div class="Image">Image Here</div>
jsfiddle 链接 HERE
最佳答案
您需要检查返回的 jQuery 对象的长度:
if (jQuery("div.type:contains('video')").length) {
jQuery(".Video").show();
jQuery(".Code").hide();
jQuery(".Image").hide();
}
查看此更新 fiddle ...
更详细一点,问题是您所有的 if
语句都返回 true,因为所有 jQuery 选择器 都返回 jQuery 对象,无论它们是否为空。 if
语句评估为 true
因为您我们只是询问 jQuery 对象 是否不是 undefined
或 假
。 jQuery 对象 两者都不是。在尝试确定是否找到任何内容时,请记住始终检查 jQuery 对象的 length
。
更新
就当 div.type
中没有任何内容时不显示任何内容而言,您可以简单地在 if
语句求值之前隐藏所有内容。类似于 this ...
关于javascript - jQuery - 寻找一个特定的词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24362171/