使用jQuery操作自定义值

时间:2013-05-17 15:30:24

标签: jquery html dom

<img src="" class="className" click="" id='button4' u="button6" r="button5" l="ele1" d="" />

我有一张图片,其中我需要更改“U”数据类型的值。 “U”数据由我正在使用的开发人员实施,我需要能够使用jQuery在每15秒的指定时间轴上的循环中更改它的值。

我可以弄清楚循环部分,但我只是想知道是否有办法使用jQuery操纵“u”值。

3 个答案:

答案 0 :(得分:2)

您可以更改u属性(顺便提一下,如果您从u切换到data-u,那么它将是有效的属性,在HTML5下) :

$('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);
});

JS Fiddle demo

虽然循环或其他变量应该如何影响新值,但由于问题本身的信息有限,因此未知。

演示如何使用允许自定义属性有效的data-*属性(在HTML5下):

<img src="http://placekitten.com/400/500" class="className" click="" id='button4' data-u="button6" data-r="button5" data-l="ele1" data-d="" />

使用以下jQuery:

$('img').attr('data-u', function (i, u) {
    return u.replace(/\d+$/,'') + (parseInt(u.replace(/\D/g, ''), 10) + 1);
});

JS Fiddle demo

参考另一个问题(Using a function to update a value within the data() method of jQuery sets the variable equivalent to the anonymous function, not the return value)中发布的答案,data()方法不接受函数作为回调,正如attr()所做的那样,这就是为什么我使用了.attr('data-u', function(){/*...*/})而不是data()方法本身(尽管我首先尝试,但这不起作用)。

参考文献:

答案 1 :(得分:1)

尝试

setInterval(function(){
    var val = $('#button4').attr('u').substring(6);
    $('#button4').attr('u', 'button' + (1 + +val))
}, 1000)

演示:Fiddle

答案 2 :(得分:0)

像这样:

$("#button4").attr("u", "new value");