开发者

jQuery .attr() multiple attributes

Attempted to retrieve attirbutes of an element using the .attr function. I dynamically create an input element using and assign the value to the class attribute.

$('.item-selection-amount').click(function(){
    console.log($(this).attr('class'));
});

This will return:

item-selection-amount ui-corner-all price
item-selection-amount ui-corner-all 66.00

price is always different, but is it possible to开发者_运维知识库 pull the third value of the class attribute such as attr('class[2]') etc?


You are using class attribute incorrectly.
It is intended to be used for visual presentation.

What you want to do is to attach data to an element.

For that purpose you can use HTML5 data- attributes:

$('.item-selection-amount').data('price', 66.00);
// ... later
$('.item-selection-amount').click(function(){
  console.log( $(this).data('price') );
});

If you want to add price to the element just render the HTML similar to one below on the server:

<li class='item-selection-item' data-price='66.00'>Something</li>


Do you have prices included in HTML as CSS classes? You can't really rely on the order of CSS class names, unless you set them up in HTML and never change in JavaScript. You should generally manipulate and test CSS classes in jQuery using .addClass(), .removeClass(), .toggleClass() and .hasClass().

For storing data consider using data- attributes:

<span class="item-selection-amount" data-price="66.00">...</span>

and it would be easy to use with jQuery:

$('.item-selection-amount').click(function(){
    console.log($(this).data('price'));
});

See DEMO. Instead of span you can use whatever tag you are using right now.


If the class always has three classes, you could split them by space and get the 3rd index.

$(this).attr('class').split(" ")[2];


If you are positive its always going to be the 3rd element in the class, you can do this:

$('.item-selection-amount').click(function(){
    console.log($(this).attr('class').split(' ')[2]);
});

This breaks the class up by spaces, and pulls out the 3rd element.

However if you are trying to store information about a product in the "class" field. A better option would be to use a data attribute, which is supported under HTML5 (and doesn't break anything in older non-HTML5 browsers). For example:

<li class="item-selection-amount" data-price="66.00">My Product</li>


Start perhaps with

var arrClasses = $(this).attr('class').split(" ");

Then you can either loop over that until you get one that matches a regex, OR, if you're confident that it'll always be in position 3 (and I wouldn't be confident) you can try as you say, and just go with

arrClasses[2]

to get the price from your example.


you can use like this

$('.item-selection-amount').click(function(){
    console.log($(this).attr('class').split(' ')[2]);
});

this is only answer what you need, but don't put any data on class tag,

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜