开发者_StackOverflowI am designing a webapp using ASP.NET and jQuery and I could use some advice.
Currently, the ASP.NET page renders an unknown number of elements that perform an action when clicked. Javascript on the front-end handles the click event based on which specific element was selected.
Each element is embedded with information that the javascript function requires. This informaion is added as extra attributes. So for example, a given element might look like
<a href="#" id="123" extrainformation="something important">Link 123</a>
jQuery then attaches a click event and uses the extrainformation
attribute as a parameter for an internal function. Each element has 3-5 parameters.
This works great, but I have heard recently that it might not be best practice since it is not WC3 compliant. One possible solution would be for each element to directly call the internal javascript function with the necessary parameters. However this makes me uncomfortable because I lose the separation of concerns between rendering the page and executing the client-side logic.
Is there a better way to do this? Or maybe I'm just overthinking it?
Yes there is a better way, its called HTML5 Data Attributes you can access them from jQuery using the $.data()
interface.
For Example:
//instead of
<a href="#" id="123" extrainformation="something important">Link 123</a>
//use
<a href="#" id="123" data-info="something important">Link 123</a>
//then access it like
var info = $('#123').data('info');
alert(info); //alerts: 'something important'
Basically anything starting with data-
is stored as data about that element in the DOM, jQuery can access this data via the $.data()
function.
精彩评论