问题描述
我正在尝试在按钮上设置一些数据,以便可以访问onclick
.我在按键值是字符串的按钮的data属性中使用JSON没问题.但是,我不知道如何将值设置为函数.
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.
单击此演示代码中的按钮后,我想让click事件调用函数option1()
,该函数将提醒字符串"hello outside".
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".
我得到的错误是:
Uncaught TypeError: Property 'option1' of object #<Object> is not a function
HTML(JSFiddle在这里: http://jsfiddle.net/NDaEh/32/):
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'
});
有什么想法吗?
推荐答案
使用以下代码获取HTML中的值:
Use the following code to get the values in your HTML:
$('button').click(function(){
var data = $.parseJSON($(this).attr('data-button'));
alert(data.option1)
});
此代码专门针对您的要求.通过这种方式,您可以将数据存储为HTML并以JavaScript代码进行检索.
This code is specifically for your requirement. By this way, you can store data in HTML and retrieve in JavaScript code.
更新了JSFiddle代码,可以在以下位置找到工作代码: http://jsfiddle.net/NDaEh/51/
Updated the JSFiddle code, working code is available at: http://jsfiddle.net/NDaEh/51/
动态调用函数的解决方案: http://jsfiddle.net/NDaEh/70/ HTML:
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]();
});
这篇关于如何使用按钮和“数据"属性以调用选定的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!