2015-10-10 55 views
1

我想从onclick事件传递属性和它们的值到JavaScript函数,但它们返回undefined。发送onclick控制到javascript函数

<script type="text/javascript"> 

function addParameters(control) { 
     alert(control._userid); 
     alert(control._flag); 
} 

<button text="Button" ID="btn1" _userid="datatest" _flag="datafromdatabaase" title="Add this to the list" onclick="addParameters(this);"> Button</button> 
+0

[使用Javascript/jQuery从HTML元素获取所有属性]的可能重复(http://stackoverflow.com/questions/2048720/get-all-attributes-from-a-html-element-with-javascript- jQuery) – Lucio

+0

你不应该使用你自己的任何属性来制作HTML中不存在的属性。改为使用自定义数据属性。 – CBroe

回答

2

您将无法访问这些自定义属性直接这样。您需要通过元素的attributes属性访问它们。试试这个:

<button text="Button" ID="btn1" _userid="datatest" _flag="datafromdatabaase" title="Add this to the list" onclick="addParameters(this);"> Button</button> 
 

 
<script type="text/javascript"> 
 

 
function addParameters(control) { 
 
    alert(control.attributes._userid); 
 
    alert(control.attributes._flag); 
 
} 
 
</script>

如果你想获得这些属性值,试试这个:

<button text="Button" ID="btn1" _userid="datatest" _flag="datafromdatabaase" title="Add this to the list" onclick="addParameters(this);"> Button</button> 
 

 
<script type="text/javascript"> 
 

 
function addParameters(control) { 
 
    alert(control.attributes._userid.nodeValue); 
 
    alert(control.attributes._flag.nodeValue); 
 
} 
 
</script>

+0

非常感谢你,我花了半天的时间试图弄明白为什么它不适用于Chrome。你真棒,再次感谢。 – JOZO

1

我建议你添加ID到按钮元素,然后使用该ID绑定单击事件侦听器:

// Html 
<button id="btn1" _userid="1" flag="true"> </button> 

//Javascript 
document.getElementById("btn1").addEventListener('click', click); 

function click(event){ 
    var attrs = event.target.attributes; 
    var userid = attrs._userid; 
    var flag = attrs._flag; 
} 

我推荐这种方法超过onclick javascript事件,因为这样你就可以将javascript与javascript分开。该html负责视图和表示数据。 JavaScript负责与视图和功能的交互。通过这种方式,数据和功能的表示是分离的和独特的。