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

javascript - Adding an "onclick" function with setAttribute() - Stack Overflow

programmeradmin4浏览0评论

Why the following is not working? Apparently the function isn't being added!

function activatetypeinput(event, devtype){
  //The function is called but it doesn't set the attribute
  var dev_input = document.getElementById("device_input");
  dev_input.setAttribute("onclick","add_device_input(event, this);");
}

In my HTML I have something like this (among other things):

<select class="text-input" id="device_input">
   <option>--</option>
</select>

Why the following is not working? Apparently the function isn't being added!

function activatetypeinput(event, devtype){
  //The function is called but it doesn't set the attribute
  var dev_input = document.getElementById("device_input");
  dev_input.setAttribute("onclick","add_device_input(event, this);");
}

In my HTML I have something like this (among other things):

<select class="text-input" id="device_input">
   <option>--</option>
</select>
Share Improve this question edited Oct 5, 2019 at 22:58 Viktor Borítás 2443 silver badges12 bronze badges asked May 14, 2018 at 0:20 FlamaFlama 8684 gold badges16 silver badges44 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

Problem


"Why the following is not working? Apparently the function isn't being added!"

dev_input.setAttribute("onclick","add_device_input(event, this);");

Explanation


Although I haven't found a reference to this specific circumstance, I'll point out what I observed:
  • Look in Devtools F12 and you'll see that the onclick attribute is added and the value as well. Although it is there and syntactically correct, it doesn't function. See section Demo - Source: #btn3

  • If the same attribute and value is added via JavaScript as a property it works, as a property. An attribute will not show up in markup, whilst a property does. For all intents and purposes, the onclick property and onclick attribute is one and the same

发布评论

评论列表(0)

  1. 暂无评论