javascript - jQuery - 寻找一个特定的词

标签 javascript jquery html css contains

我正在尝试根据元框(下拉列表)的值在 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 对象 是否不是 undefinedjQuery 对象 两者都不是。在尝试确定是否找到任何内容时,请记住始终检查 jQuery 对象的 length

更新

就当 div.type 中没有任何内容时不显示任何内容而言,您可以简单地在 if 语句求值之前隐藏所有内容。类似于 this ...

关于javascript - jQuery - 寻找一个特定的词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24362171/

相关文章:

javascript - 悬停子元素时保持父元素的 CSS 样式

Javascript 函数未被调用 hx :commandExButton 的 onclick

javascript - 尝试使用 JQUERY 用 JSON 数据填充 Select

javascript - 在构建 ajax 应用程序时放弃 <form> 标记是否合适?

javascript - 移动对象以使用 Canvas 单击 X 和 Y

javascript - 动态下拉菜单不会填充正确的内容

javascript - jQuery 选择器仅第一级 div

javascript - 基于某些变量的 Bootstrap 上下文表

javascript - 使用javascript替换网页上的文本

html - 滚动背景的名称是什么?