问题
In a previous life, I might have done something like this:
<a href="#" onclick="f(311);return false;">Click</a><br/>
<a href="#" onclick="f(412);return false;">Click</a><br/>
<a href="#" onclick="f(583);return false;">Click</a><br/>
<a href="#" onclick="f(624);return false;">Click</a><br/>
Now with jQuery, I might do something like this:
<a class="clicker" alt="311">Click</a><br/>
<a class="clicker" alt="412">Click</a><br/>
<a class="clicker" alt="583">Click</a><br/>
<a class="clicker" alt="624">Click</a><br/>
<script language="javascript" type="text/javascript">
$(".clicker").bind("click", function(e) {
e.preventDefault();
f($(this).attr("alt"));
});
</script>
Except that using the alt attribute to pass the data from the DOM to jQuery feels like a hack, since that's not its intended purpose. What's the best practice here for storing/hiding data in the DOM for jQuery to access?
回答1:
JQuery.data lets you associate a dictionary to a DOM element. This data can be set via jQuery:
<a class="clicker">Click</a><br/>
<a class="clicker">Click</a><br/>
<a class="clicker">Click</a><br/>
<a class="clicker">Click</a><br/>
<script language="javascript" type="text/javascript">
var values = new Array("311", "412", "583", "624");
$(".clicker").each(function(i, e) {
$(this).data('value', values[i]).click(function(e) {
f($(this).data('value'));
});
});
</script>
or (since jQuery 1.4.3) using the HTML5 data- attributes, which work even in non-HTML5 documents:
<a class="clicker" data-value="311">Click</a><br/>
<a class="clicker" data-value="412">Click</a><br/>
<a class="clicker" data-value="583">Click</a><br/>
<a class="clicker" data-value="624">Click</a><br/>
<script language="javascript" type="text/javascript">
$(".clicker").click(function(e) {
f($(this).data('value'));
});
</script>
回答2:
You could use an id attribute like "clicker-123" then parse out the number. I usually do that or use the 'rel' attribute.
So, in essence, there is no better way to do it that I know of. I hope this thread proves me wrong.
回答3:
You'll best use a new feature of HTML5: the data-...
-attribute.
Your html-code will look like this:
<a class="clicker" data-mynumber="311">Click</a>
Then you can use el.attr('data-mynumber')
to get the data.
Instead of mynumber, you can choose any name.
This works in all browsers.
回答4:
I'm sorry, but if you are already filling in the alt tag, I fail to see how delaying the assignment of the onclick handler to jQuery actually buys you anything. Isn't this just a case of "Now that I have a hammer, every problem looks like a nail." I think the jquery method is best used when the action does not depend on extra data than what can naturally be derived from the content, for example, class definition, tag type, etc.
来源:https://stackoverflow.com/questions/364412/associating-data-to-a-dom-element-for-jquery