开发者

Can I stick extra stuff in HTML tags so that my JQuery can pick up on it?

开发者 https://www.devze.com 2023-01-28 07:53 出处:网络
<div id=\"holder\" rel=\"http://mysite.com/go.jpg\" rel2=\"42pixels\" 开发者_高级运维rel3=\"gaga\">
<div id="holder" rel="http://mysite.com/go.jpg" rel2="42pixels" 开发者_高级运维rel3="gaga">
blah
</div>

Is this allowed?


If possible, I would recommend using HTML5's custom data attributes to achieve this:

<div id="holder" rel="http://mysite.com/go.jpg" data-rel2="42pixels" data-rel3="gaga">
    blah
</div>


The common approach for this scenario is to employ the data-* pseudo-namespace.

This doesn't validate in all version of HTML; but it's relatively innocuous and very handy; and a lot better than a lot of other approaches.

Edit: Examples are always great:

<!-- In an HTML file loaded with AJAX, for instance: -->
<ul>
  <li data-id="1">My Little Pony</li>
  <li data-id="2">Transformers</li>
</ul>


The data-* attribute is the proper way to add custom attributes, but that is only valid in HTML5. Personally, I usually use either the id or the class attributes to pass extra data. In your case, you could even do something like:

<div id="holder" class="http://mysite.com/go.jpg_42pixels_gaga">blah</div>

and then use something along these lines to access that data:

var divParams = $("#holder").attr("class").split('_');
alert('Param 1 is: ' + divParams[0] + ' / Param 2 is: ' + divParams[1] + ' / Param 3 is: ' + divParams[2]);

Of course, you might want to use a more complex separator than the underscore to make sure you don't split the string wrong, I just used it as POC.

Hope this helps !


No, it won't validate that way: http://www.alistapart.com/articles/scripttriggers/

You could provide a custom DTD to make it "valid": http://www.alistapart.com/articles/customdtd/


Depends what you mean by "allowed". It'll work, but your validation will be shot. The class attribute was intended to cover these kind of extensions (though nobody really uses it for anythign but CSS, so it's arguably become de facto abusive to do so).

0

精彩评论

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