最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to pass array to a setAttribute method in javascript - Stack Overflow

programmeradmin0浏览0评论

I want to pass few parameters to setAttribute() method parameters are :

var obj = string/this;
var mal_pat_id = "avx";
instruction = "some_instruction";
line = ['a','b','c'];

var newSelect = document.getElementById("dialog_ok_btn_for_mal_pat_conf_yes");

newSelect.setAttribute('onclick', "add("+ obj +","+ mal_pat_id + "," +    instruction + "," + line + ")");

parameter line is passed as a string, which should be passed as an array.

Thank you in advance.

I want to pass few parameters to setAttribute() method parameters are :

var obj = string/this;
var mal_pat_id = "avx";
instruction = "some_instruction";
line = ['a','b','c'];

var newSelect = document.getElementById("dialog_ok_btn_for_mal_pat_conf_yes");

newSelect.setAttribute('onclick', "add("+ obj +","+ mal_pat_id + "," +    instruction + "," + line + ")");

parameter line is passed as a string, which should be passed as an array.

Thank you in advance.

Share Improve this question edited Feb 14, 2017 at 10:58 Zakaria Acharki 67.5k15 gold badges78 silver badges106 bronze badges asked Feb 14, 2017 at 10:54 Rohan NagalkarRohan Nagalkar 4432 gold badges6 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

You should use the addEventListener() method instead :

newSelect.addEventListener("click", function(){
    add(obj, mal_pat_id, instruction, line);
});

Hope this helps.

Why use set attribute for event listening. Do it directly using onclick property like this:

newSelect.onclick = function() {
      add(obj, mal_pat_id, instruction, line);
}

Or better like this:

newSelect.addEventListener("click", function() {
      add(obj, mal_pat_id, instruction, line);
});

Note: This is not available for all kind of attributes.

You can achieve what you want by surrounding the array with "[]" this will make it seem like an array to the function

newSelect.setAttribute('onclick', "add("+ obj +","+ mal_pat_id + "," +instruction + "," +"[" +line+ "]"+ ")");

This will set all the array elements of the array line as ['a','b','c'] instead of setting them as 'a','b','c' which will make the function identify them as individual variables

发布评论

评论列表(0)

  1. 暂无评论