2016-03-29 14 views

答えて

6

これは、jQueryのattr()方法で行うことができます。

var someValue = 2560; 
$('.priceinfo.col5').attr('data-price', someValue); 

あなたはattr()を使用して、そのようなHTML5 data-属性などのカスタム属性を含む任意の属性を設定することができます。


ます。またpass a function代わり.attr()に固定された値のことができます:jQueryのセット内に複数の要素がある場合

$('.priceinfo.col5').attr('data-price', function() { 
    var text = $(this).text(); 
    return parseInt(text, 10); //drops the non-numeric characters at the end of the text 
}); 

これは非常に便利です - クラスpriceinfocol5を持つ複数の要素が。


値は時々、最初の数字以外の文字を持っている可能性がある場合は、あなたがテキストを解析するためにregular expressionを使用することができますが:

$('.priceinfo.col5').attr('data-price', function() { 
    var text = $(this).text(); 
    var matches = /\d+/.exec(text); 
    if (!matches) {return '';} 
    return parseInt(matches[0], 10); 
}); 
+0

こんにちは!私は、要素の文字列からデータ値を作成したいと思います。これは動的な数字なので、スクリプトで値を自分で設定することはできません。 –

+0

それは素晴らしい仕事でした!ありがとう –

+0

@Zev Spitz私は文字列の数字の前に数字以外の文字がある状況を認識しました。 –

0

あなたにもプレーンなJavaScriptでそれを行うことができます。

function setAttribute(selector, attribute, value) { 
    var elements = document.querySelectorAll(selector); 
    for (var index = 0; index < elements.length; index++) { 
     elements[index].setAttribute(attribute, (typeof value === "function" ? value(elements[index] : value))); 
    } 
} 
関連する問題