What is the recommended practice to send information from the server to a jQuery script?
At the moment my server outputs HTML that looks something like this:
<span class='tag'>music<a href='' onclick='return remove_tag(73)'>×</a></span>
<span class='tag'>concert<a href='' onclick='return remove_tag(42)'>×</a></span>
<span class='tag'>theatre<a href='' onclick='return remove_tag(101)'>×</a></span>
Of course, the numbers in the JavaScript are database IDs which the server understands.
Now, I’m told that it is not good practice anymore to put JavaScript onclick handlers into the HTML, but instead to bind them in jQuery:
<span class='ta开发者_运维百科g'>music<a href=''>×</a></span>
<span class='tag'>concert<a href=''>×</a></span>
<span class='tag'>theatre<a href=''>×</a></span>
[...]
$(".tag a").click(function() { return remove_tag( ??? ); })
But now where do I put those IDs for each tag? What is the recommended practice for this?
If you can use jQuery 1.4.3+ you can use the data-* attributes.
<span class='tag'>music<a href='' data-id="73">×</a></span>
and then in jQuery
$(".tag a").click(function() {
return remove_tag( $(this).data("id") );
});
Example on jsfiddle
I usually end up putting them in a data attribute, like:
<span class='tag'>music<a href='' data-tag-id="73">×</a></span>
<span class='tag'>concert<a href='' data-tag-id="42">×</a></span>
<span class='tag'>theatre<a href='' data-tag-id="101">×</a></span>
Then in the javascript you do:
$(".tag a").click(function() { return remove_tag( $(this).data('tag-id') ); })
Use html 5 data tags, which jQuery can then read.
<span class="tag" data-tagid="73">music<a href="">×</a></span>
For more information: http://ejohn.org/blog/html-5-data-attributes/
You could use HTML5 data-* Attributes
By the way, there's more problem if you are following best practices. You should use unobtrusive javascript because in cases javascript is turned off when viewing your page, html should be fully functional. I mean, in your case, i would not leave those <a>
s with blank href, and would give them functional links, which would lead to tag removal comfirmation page
You can just output a data attribute data-tagId
and the value of this id will be from database, something like this.
<span class='tag'>music<a href='#' data-tagId='73'>×</a></span>
On client side attach the event like this and get the data attribute value.
$(".tag a").click(function() { return remove_tag($(this).data('tagId')); });
精彩评论