0

当我点击一个链接时,我将它的 href 值放在一个变量中(数字代表一个唯一的 id),然后......我有一个单独的 ul:

<ul class="class_one">
   <li class="class_two"><a href="2345">some text</a></li>
   <li class="class_three"><a href="6789">some text</a></li>
</ul>

我想要做的是看看我的“ul”中是否有任何“a”,它具有与我存放在变量中的相同的 id。

我尝试了这样的事情(当然没有结果):

$('ul.class_one').find('a[href="' + myVar + '"]')
//and if it finds no element do something
//i think is something wrong with the quotes ('a[href="' + myVar + '"]')
4

3 回答 3

1

你试过交换你的报价吗?jQuery 可能使用单引号进行属性选择匹配...

$('ul.class_one').find("a[href='" + myVar + "']");

来自jQuery 文档

一个属性值。在大多数情况下,引号是可选的,但当值包含像“]”这样的字符时,应该使用引号来避免冲突。可以使用以下语法使用变量: [name='" +MyVar+ "']

于 2009-10-22T22:02:54.140 回答
1

可以完全删除引号...

$('ul.class_one').find('a[href='+myVar+']');

应该管用

于 2009-10-22T22:04:59.177 回答
-2

CSS 和扩展的 jQuery 使用单引号。

$("ul.class_one").find("a[href='" + myVar + "']");
于 2009-10-22T22:02:22.997 回答