最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically give HTML element a custom attribute - Stack Overflow

programmeradmin3浏览0评论

Is it possible to give a HTML element a new custom attribute?

You know how a "img" html element has the attribute .src:

imgEle.src = "";

Can I dynamically give a HTML element my own custom attribute .animationInterval? Is it as simple as this?...

imgEle.animationInterval = setInterval(...,10);

Maybe I do it the xml kindof way?...

imgEle.setAttribute("animationInterval", setInterval(...));

Whats the best way to do this?

Is it possible to give a HTML element a new custom attribute?

You know how a "img" html element has the attribute .src:

imgEle.src = "";

Can I dynamically give a HTML element my own custom attribute .animationInterval? Is it as simple as this?...

imgEle.animationInterval = setInterval(...,10);

Maybe I do it the xml kindof way?...

imgEle.setAttribute("animationInterval", setInterval(...));

Whats the best way to do this?

Share asked Dec 31, 2011 at 0:51 sazrsazr 25.9k70 gold badges214 silver badges387 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

The best way is to use html5 data- attributes:

$(imgEle).attr("data-animateinterval", "12");

Which can then be read back with

$(imgEle).data("animateinterval");

Which of course can also be added directly to your markup

<img src="foo.png" data-animateinterval="12" />

Also, if you're not concerned about whether a new attribute is added to the actual html element, but just want some arbitrary data associated with it, you can simply do this:

$(imgEle).data("animateinterval", "12");

And retrieve it like this:

var animateInterval = $(imgEle).data("animateinterval");

Note however that as Esailija explains, this may or may not actually add a new attribute to your element; it may just store this data internally. If that's not a concern for you, and I can't think of any reasons why it should be, then you may prefer this more succinct syntax.

To be clear, no matter which way you store it, $(imgEle).data("animateinterval"); will still work just fine.

The first way (element.something) sets a property and can be anything.

Th second way (element.setAttribute) sets an attribute, which must be a string (or serialisable as one via its toString() method).

So in this case either way works, but I would remend the first.

发布评论

评论列表(0)

  1. 暂无评论