jQuery属性选择器-我做错了吗? [英] jQuery attribute selector - am I doing something wrong?

查看:63
本文介绍了jQuery属性选择器-我做错了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var selector = "ul.lower-menu li a[innerText=\"" + PanelSettings[tab_name_key] + "\"]";

我试图获取水平菜单选项卡,该菜单选项卡将innerText属性设置为先前存储的值.

I'm trying to get horizontal menu tab that has innerText property set to the previously stored value.

配置值的存储方式如下:

The config value is stored like this:

PanelSettings[tab_name_key] = $("ul.lower-menu li:first > a").prop("innerText");

它实际上在那里,并且始终具有适当的值.

It is actually there and it always has the proper value.

我从jQuery中什么也没得到-我在这里做错了什么吗?

I get nothing from jQuery - am I doing something obviously wrong here?

我正在使用jQuery 1.6.4

I'm using jQuery 1.6.4

推荐答案

是的,您做错了什么.属性选择器选择具有特定属性设置的元素. innerText属性,不是属性-实际上,您可以通过使用prop对其进行设置来识别.

Yes, you are doing something wrong. The attribute selector selects elements that have a certain attribute set. innerText is a property, not an attribute – as indeed you recognise by using prop to set it.

您有两个选择.一种是使用:contains选择器:

You have two options. One is to use the :contains selector:

"ul.lower-menu li a:contains(" + PanelSettings[tab_name_key] + ")"

但是,如果您要求输入foo,它将选择foobar.更好的选择是使用filter:

This, however, would select foobar if you asked for foo. The better option is to do the filtering yourself, using filter:

var selector = "ul.lower-menu li a";
var els = $(selector).filter(function() {
    return $.text([this]) === PanelSettings[tab_name_key];
});

这仅选择文本内容与给定设置相同的元素.

This selects only the elements whose text content is the same as the setting given.

NB也应该使用text()而不是prop('innerText').

NB also, as Diodeus says, you should use text() rather than prop('innerText').

这篇关于jQuery属性选择器-我做错了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆