开发者

Pass lots of data from a single anchor tag

What is the best way to pass a lot of data from a single link? Is something like this a good idea or is there a better way?

<a href="{ 'id':'1', 'foo':'bar', 'something':'else' }" id="myLnk" > Click </a>


$('#myLnk).click( function(event){
开发者_如何学Go  event.preventDeafult();
  var data = $(this).attr('href')
  console.log( $.parseJSON( response ) );

})

Thanks!


The best way to do this is probably to use custom data attributes in your anchor tag.

For example:

<a href="#" data-json="{ 'id':'1', 'foo':'bar', 'something':'else' }">Click</a>

You can then easily access this data from your JavaScript using the jQuery data() function.

Or, rather than bundling all the data together in a single JSON block, you can split it into separate attributes:

<a id="myLnk"
    data-id="1"
    data-foo="bar"
    data-something="else">

These can then be retrieved using jQuery like this:

$("#myLnk").data("id")
$("#myLnk").data("foo")
$("#myLnk").data("something")


The recommended way is to use HTML5 data-* attributes:

<a href="#" id="myLnk" data-id="1" data-foo="bar" data-something="else">Click</a>


To add to Chris's & MvChr's responses, you can also do this, although I hate using single quotes for attributes:

<a href='#' data-json='{ "id":1, "foo":"bar", "something":"else" }'>Click</a>

The reason for this syntax is because if you quote it properly, $.data in jQuery will automatically work. Otherwise, you have to $.parseJSON($.data(selector)) the information.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜