如何获取元素属性的参数值?

时间:2018-04-03 13:22:46

标签: javascript regex

我有一个元素说:

<button id="buttonId" class="someClass anotherClass" onclick="javascript:somefunction('param1', 'param2')">
</button>

我想要的是一种获取价值的方法&#39; param1&#39;和&#39; param2&#39;。有没有办法只用javascript(而不是jQuery)才能得到这个?

我通过以下方式获取值:

var value = document.getElementById('buttonId').getAttribute('onclick');

3 个答案:

答案 0 :(得分:1)

var value = document.getElementById('buttonId').getAttribute('onclick');
console.log(value.split(/\(|\)/g)[1].split(/,\s*/g));
<button id="buttonId" class="someClass anotherClass" onclick="javascript:somefunction('param1', 'param2', 'param3')">Click
</button>

答案 1 :(得分:1)

试试这个。可能很容易理解

&#13;
&#13;
var attr =  document.getElementById("buttonId").getAttribute("onclick")  
console.log(attr.split("(")[1].split(")")[0].split(",").map(function (el) {
  return el.trim();
}))
&#13;
<button id="buttonId" class="someClass anotherClass" onclick="javascript:somefunction('param1', 'param2', 'param3')">Click
</button>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

让我们实现一个知道其参数的函数:

function wrapper() {
    //Here I am logging it to the console, but one can do virtually anything with arguments
    console.log(arguments);
    //If you want to execute somefunction, then uncomment the next line
    //somefunction.call(arguments);
}

现在让我们确保您拨打wrapper而不是somefunction

eval(button.attributes['onclick'].value.substring(11).replace('somefunction', 'wrapper'));