how to get information from tag <a>'s action-data?
-
28-10-2019 - |
Question
I want to put some information in the "action-data" of a href, like:
<a href=# action-data="userid={{g.user._id}}&messageid={{message._id}}" id=reply >reply</a>
but how to get the userid & messageid back to Javascript code?
<script type=text/javascript>
$(function () {
$('a#reply').bind('click', function () {
$.getJSON($SCRIPT_ROOT + '/_get_replies', {
messageid: ??????How to get messageid from href action-data?
userid: ??????How to get userid from href action-data?
}, function (data) {
$('#replies').text(data.result)
});
return false;
});
});
Solution
store it differently:
<a href="#"data-userid="{{g.user._id}}" data-messageid="{{message._id}}" id="reply">reply</a>
jQuery can get it like this:
var messageId = $('#reply').data('messageid');
Also, the click event can be much shorter:
$('a#reply').click(function(){
});
ps: remember to use quotes, as you didn't in href
and id
OTHER TIPS
If you control the markup, you should prefix attributes with data-
, not suffix them with -data
. Also, it seems easier to have one attribute for each property, instead of parsing, so why not:
<a href=# data-userid="{{g.user._id}}" data-messageid="{{ message._id }}" id=reply>
Then you can use jQuery data
:
var userid = $("a#reply").data("userid"),
messageid = $("a#reply").data("messageid");
I also recommend the other answerer's recommendations about using different markup. However, if you can't change the markup you can parse the parameters like this:
...
$('a#reply').click(function() {
// parse the 'action-data' attribute of the link
var actionData = $(this).attr('action-data');
var params = {};
$.each(actionData.split("&"), function(index, data) {
var keyValue = data.split("=");
params[keyValue[0]] = keyValue[1];
});
// now you can use params.userid and params.messageid
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow