私はこの質問に答えました: jQuery でカスタム値を操作する
このjQueryでは:
$('img').attr('u', function(i,u) {
/* i is the index of the current image among all the images returned by the selector,
u is the current value of that attribute */
return u.slice(0, -1) + (parseInt(u.replace(/\D/g,''), 10) + 1);
});
answer へのリンク、その answer からのJS Fiddle demo。
data-*
しかし、 HTML5 で許可されているカスタム属性 (無効ではあるが機能するカスタム属性ではなく)を使用して、「適切に」それを行う方法を示す必要があると感じたので、HTML を次のように変更しました。
<img src="http://placekitten.com/400/500" class="className" click="" id='button4' data-u="button6" data-r="button5" data-l="ele1" data-d="" />
(いいえ、このclick
属性が何を意味するのか、なぜそこにあるのかわからないので、そのままにしておきました。)
そして、次のjQueryをテストしました:
$('img').data('u', function(i,u) {
/* i is the index of the current image among all the images returned by the selector,
u is the current value of that attribute */
return u.slice(0, -1) + (parseInt(u.replace(/\D/g,''), 10) + 1);
});
$('img').each(function(){
console.log($(this).data('u'));
});
さて、data()
メソッドを使用すると、属性が更新されないことがわかりました。そのため、を使用しconsole.log()
て更新された値を確認しましたが、出力は無名関数自体であり、そこから返されると予想される値ではありません関数。これがバグである可能性は低く、おそらく予想される動作であることは理解していますが、匿名関数を使用して、たとえば 、 などで使用されるのと同じ方法で属性を更新する方法はありattr()
ますtext()
か?