javascript 从单个锚标记传递大量数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6085354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:23:40  来源:igfitidea点击:

Pass lots of data from a single anchor tag

javascriptjqueryobject

提问by Pardoner

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){
  event.preventDeafult();
  var data = $(this).attr('href')
  console.log( $.parseJSON( response ) );

})

Thanks!

谢谢!

回答by Chris Fulstow

The best way to do this is probably to use custom data attributesin 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.

然后,您可以使用 jQuery data()函数从 JavaScript 轻松访问此数据。

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

或者,不是将所有数据捆绑在一个 JSON 块中,您可以将其拆分为单独的属性:

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

These can then be retrieved using jQuery like this:

然后可以像这样使用 jQuery 检索这些:

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

回答by mVChr

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

推荐的方法是使用 HTML5data-*属性:

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

回答by John Green

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

要添加到 Chris 和 MvChr 的回复中,您也可以这样做,尽管我讨厌对属性使用单引号:

<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.

这种语法的原因是因为如果你正确引用它,jQuery 中的 $.data 将自动工作。否则,你必须 $.parseJSON($.data(selector)) 的信息。