[英]jQuery, Select by attribute value, adding new attribute
I have an anchor in my HTML. 我的HTML中有一个锚点。 it has a page attribute with a value.
它有一个带有值的页面属性。 So everytime it is clicked I use the page attribute value in my js.
所以每次点击它我都会在我的js中使用页面属性值。 Now I want to set a style attribute with a background color to show that a certain a element is selected.
现在我想设置一个带有背景颜色的样式属性,以显示选择了某个元素。 So I have to select the element by page attribute and add a new attribute with a value to the a element.
所以我必须选择逐页元素属性,并为a元素添加一个带有值的新属性。
How do I handle that? 我该如何处理?
With HTML like: 使用HTML像:
<a href='#' page='1'>Link 1</a><br />
you could do: 你可以这样做:
$('a[page=1]').addClass('selected').attr('test', 'hi!');
(ie better to change display using a css class [eg 'selected'] than the style attribute - but the attr call there shows how to add an attribute). (即更好地使用css类[例如'selected']而不是style属性来更改显示 - 但是那里的attr调用显示了如何添加属性)。
To select an element by attribute value, you can use this syntax: 要按属性值选择元素,可以使用以下语法:
$('[attribName="value here"]')
Where attribName
should be replaced with attribute name such as name
, title
, etc. 其中
attribName
应替换为属性名称,如name
, title
等。
To add a new attribute value, you can use the attr
method. 要添加新属性值,可以使用
attr
方法。
Example: 例:
$('[attribName="value here"]').attr('attribute name', 'attribute value');
And this is how you can change the background color: 这就是你可以改变背景颜色的方法:
$('[attribName="value here"]').css('background-color', 'green');
Note you should replace dummy attribute names and values as per your requirements. 请注意,您应根据您的要求替换虚拟属性名称和值。
不确定你在问什么..你需要找到具有“页面”特定值的元素并更改其背景吗?
$("a[page='value']").css('background-color', 'color-code');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.