我有一个简单的 HTML 模板,在整个文档中多次使用。它本质上是以下 div
元素,包裹着几个 p
元素和另一个具有 button
类的 div
元素。出于可视化目的,这里有一个示例:
<div class="content">
<p>First paragraph</p>
<p>Second paragraph</p>
<div><a class="button" href="http://www.apple.com/ipad/">Change me jQuery!</a></div>
</div>
<div class="content">
<p>First paragraph</p>
<p>Second paragraph</p>
<div><a class="button" href="http://www.apple.com/iphone/">Change me jQuery!</a></div>
</div>
现在,使用此模板在网站上发布内容的用户并不总是会在该 anchor 标记中使用完全相同的 URL,但我确实知道他们可以使用哪些 URL。所以我想用我的代码做如下:
- 内容发布且 anchor 标记给出网址后 地址,我想检查该地址并看看是否有特定的 里面的话。如果找到该单词,则将 anchor 文本更改为我选择的内容。
- 再次执行相同操作,但这次检查网址字符串中是否有不同的单词。
这是我写的:
$('.content').each(function () {
var $this = $(this),
$findP = $this.find('p');
if ($findP.length > 2) {
// Run some code
} else if ( ($findP.length <= 2) && ($('a[href*="ipad"]')) ) {
$this.find('a.button').text('Visit iPad site');
} else if ( ($findP.length <= 2) && ($('a[href*="iphone"]')) ) {
$this.find('a.button').text('Visit iPhone site');
}
});
问题:
- 两个 anchor 标记的文本仅更改为我在
.text()< 内的第一个 else if 语句中编写的文本字符串
jQuery 方法。在我的示例中,第一个 anchor 标记应采用文本“访问 iPad 网站”,而第二个 anchor 标记应采用“访问 iPhone 网站”。这是此示例的工作 fiddle : http://jsfiddle.net/vj4xZ/1/
我猜测问题在于,一旦找到第一个元素,所有 anchor 标记都会被分配 .text() 方法中的内容,并且代码就在那里停止,而不查找第二个 else 中的内容if 语句。如果是这样,或者手头的问题是其他的,那么我怎样才能让它正常工作呢?对此的任何帮助将不胜感激。感谢您的宝贵时间!
最佳答案
http://jsfiddle.net/zerkms/vj4xZ/2/
您需要将条件更改为:
} else if ( ($findP.length <= 2) && ($this.find('a[href*="ipad"]').length) ) {
$('a[href*="ipad"]')
- 表示 - 如果文档中某处的 href 中有带有 ipad
的 anchor
我所做的更改 - 仅使用 $this.find()
您也可以使用 $('a[href*="ipad"]', $this)
代替,它会执行相同的工作
关于javascript - jQuery 中选择器和条件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10792883/