【问题标题】:jQuery, Select by attribute value, adding new attributejQuery,按属性值选择,添加新属性
【发布时间】:2023-03-04 19:24:01
【问题描述】:

我的 HTML 中有一个锚点。它有一个带有值的页面属性。因此,每次单击它时,我都会在我的 js 中使用页面属性值。现在我想设置一个带有背景颜色的样式属性来显示某个元素被选中。所以我必须按页面属性选择元素,并向 a 元素添加一个带有值的新属性。

我该如何处理?

【问题讨论】:

  • 请给我们看代码。

标签: javascript jquery jquery-selectors


【解决方案1】:

像 HTML 一样:

<a href='#' page='1'>Link 1</a>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​<br />

你可以这样做:

$('a[page=1]').addClass('selected').attr('test', 'hi!');​

(即使用 css 类 [例如'selected'] 比样式属性更好地更改显示 - 但是那里的 attr 调用显示了如何添加属性)。

【讨论】:

  • but I want to have the selected a element to have selected class, all other elements should not have this class, so how do I remove the class when an other element is selected?
【解决方案2】:

要按属性值选择元素,可以使用以下语法:

$('[attribName="value here"]')

其中attribName应替换为nametitle等属性名称。

要添加新的属性值,可以使用attr 方法。

示例:

$('[attribName="value here"]').attr('attribute name', 'attribute value');

这就是你可以改变背景颜色的方法:

$('[attribName="value here"]').css('background-color', 'green');

请注意,您应该根据自己的要求替换虚拟属性名称和值。

【讨论】:

    【解决方案3】:

    不确定你在问什么..你需要为“page”找到具有特定值的 a 元素并更改其背景吗?

    $("a[page='value']").css('background-color', 'color-code');
    

    【讨论】:

    • 感谢它的工作原理,但是当我单击另一个 a 元素时,我在颜色代码中指定的颜色仍然存在。它应该切换回默认值。知道怎么做吗?
    • 您使用 null 取消设置 css 属性。 $("a[page='value']").css('background-color', null).
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多