How to use a button's “data-” attribute to call a selected JavaScript function

社会主义新天地 提交于 2019-12-03 06:03:02

问题


I'm trying to set some data on my buttons such that it can be accessed onclick. I'm having no problem using JSON in a button's data attribute where the key value is a string. However, I can't figure out how to set the values to be a function.

What I'd like to happen upon clicking the button in this demo code is for the click event to call the function option1() which will alert the string "hello outside".

The error I'm getting is this:

Uncaught TypeError: Property 'option1' of object #<Object> is not a function

HTML (JSFiddle is here: http://jsfiddle.net/NDaEh/32/):

<button type='button' data-button='{"option1": "option1", "option2": 
"option2"}'>click1</button>

JS:

var data='hello outside';
var option1=function(data){
    alert(data)
}  

$('button').click(function(){
  //var data='hello inside';
  $(this).data('button').option1(data); // should alert 'hello outside'
});

Thoughts?


回答1:


Use the following code to get the values in your HTML:

$('button').click(function(){
  var data = $.parseJSON($(this).attr('data-button'));
  alert(data.option1)
});

This code is specifically for your requirement. By this way, you can store data in HTML and retrieve in JavaScript code.

Updated the JSFiddle code, working code is available at: http://jsfiddle.net/NDaEh/51/

EDIT:

Solution to call a function dynamically: http://jsfiddle.net/NDaEh/70/ HTML:

<button type='button' data-button='{"func": "func1"}'>click1</button>
<button type='button' data-button='{"func": "func2"}'>click2</button>

JS:

var myFuncs = {
  func1: function () { alert('Function 1'); },
  func2: function () { alert('Function 2'); },
};

$('button').click(function(){
  var data = $.parseJSON($(this).attr('data-button'));

  myFuncs[data.func]();
});



回答2:


Dont save objects as JSON strings in the html tag property value. Use the data() method instead.

$('input[type="button"]').data({ option1: 'o1', option2: 'o2' });

Also, when youre writing this:

$(this).data('button').option1(data);

option1 would need to be a plugin in order to be chained on to the data method (or any jquery method for that matter). You would need tomething like this:

jQuery.fn.option1 = function () {

   alert($(this).data('option1'));

   return this;
}

Fiddle




回答3:


Use the jQuery data as shown below:

$('input[type=button]').data('button-data', { option1: 'option1', option2: 'option2});

Use:

$('input[type=button]').data('button-data');  //{ option1: 'option1', option2: 'option2}

In order to get the data from the element



来源:https://stackoverflow.com/questions/12835550/how-to-use-a-buttons-data-attribute-to-call-a-selected-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!