jQuery, Select by attribute value, adding new attribute

后端 未结 3 1409
南旧
南旧 2021-01-22 14:10

I have an anchor in my HTML. it has a page attribute with a value. So everytime it is clicked I use the page attribute value in my js. Now I want to set a style attribute with a

相关标签:
3条回答
  • 2021-01-22 14:13

    Not sure what you're asking.. do you need to find the a elemenent with a certain value for "page" and change its background?

    $("a[page='value']").css('background-color', 'color-code');
    
    0 讨论(0)
  • 2021-01-22 14:28

    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.

    To add a new attribute value, you can use the attr method.

    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.

    0 讨论(0)
  • 2021-01-22 14:38

    With HTML like:

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

    you could do:

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

    (i.e. better to change display using a css class [e.g. 'selected'] than the style attribute - but the attr call there shows how to add an attribute).

    0 讨论(0)
提交回复
热议问题