I'm trying to use jQuery to add some css to elements, but only if they have a certain attribute.

The reason why I'm not using just css is because the content for the site is too vast to go through and add classes to all the elements I want to style.

The jQuery code I'm using is this:

if ($('.body_text a').attr('name')) {
    $(this).css({
        'display': 'inline-block',
        'position': 'relative',
        'top': '-200px',
        'visibility': 'hidden'
    })
}

But this doesn't seem to be working. If I put an alert inside the if statement the alert works. Am I doing something wrong?

有帮助吗?

解决方案

This is the jQuery selector you're looking for:

//de or: $('.body_text a[name="value"]').css({
$('.body_text a[name]').css({
    'display': 'inline-block',
    'position': 'relative',
    'top': '-200px',
    'visibility': 'hidden'
})

http://api.jquery.com/attribute-equals-selector/

You can do this with CSS too:

.body_text a[name] {
    display: inline-block;
    position: relative;
    top: -200px;
    visibility: hidden;
 }

http://www.w3schools.com/css/css_attribute_selectors.asp

其他提示

It's because $(this) doesn't actually refer to anything — It needs to be placed in a function to refer to something.

However, the following code goes through all as with a name attribute, and applies the styles to each one.

$('.body_text a[name]').css({
     'display': 'inline-block',
     'position': 'relative',
     'top': '-200px',
     'visibility': 'hidden'
})

Viewing the documentation:

The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

I guess this is your problem?

Try this it should do the trick:

if( $('.body_text a').attr('name') == "TEXT HERE" ){
     // Do something
} else {
     // Do Something else
}

Make sure to loop through using the .each on the element you are looking for.

$('.body_text a').each(function(){
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top