使用 setAttribute() 添加“onclick”函数

2024-05-17

为什么以下不起作用? 显然该功能尚未添加!

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);");
}

在我的 HTML 中,我有这样的内容(除其他外):

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


Problem --

“为什么以下不起作用?显然该功能没有添加!”

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 not. For all intents and purposes, the onclick property and onclick attribute is one and the same????.

  • 此行为是 jQuery 方法的标准行为attr() and prop()。作为一个例子,我经常看到这样的情况:

    ???? $(":checkbox").prop("checked", true);

    ???? $(":checkbox").attr("checked", true);


Event Handling ----
Events are registered to either an element within the DOM or browser related Non-DOM Object like Window. There are 3 types of event registration:
  1. 事件属性:古老得像泥土一样,普遍受到网络开发社区的劝阻和皱眉。这是 OP 代码尝试以编程方式创建的事件处理程序类型setAttribute()方法。看来,一个on event是遥不可及的set/get/removeAttribute()方法和最可能的 jQuery 方法attr()以及(未经测试,也不那么好奇)。请参阅部分:演示 - 来源:#btn0

    <button onclick="funcName(event)">Discouraged</button>
    

2. ⭐ **On-event Property:** This is event handling is old and looked down upon as well but because it's limited compared to its predecessor *Event Listener*. **An onclick property and onclick attribute are one and the same as far as DOM elements are concerned. Use this and not `setAttribute()`.** ***See section Demo - Source: `#btn1`***

document.getElementById('id').onclick = funcName;


3. **Event Listener:** This type of event handling employs the methods `add/removeEventListener("event", funcName)` and is the most standard, current, and preferred way. ***See section Demo - Source: `#btn2`***

document.getElementById('id').addEventListener("event", funcName);


For details why the first 2 types of event handling are reviled, read **[DOM on-event handlers][1]** for the technical reasons and this **[Reddit article][2]** for development and design oriented reasons. I'm personally ambivalent about the subject because on-event handlers aren't deprecated and concepts such as separation of presentation, behavior, structure, semantics, etc. are not as important as they were before.

##解决方案


Other than using an On-event Property???? we can parse a htmlString of the entire element with the onclick attribute. This can be done using:

  • innerHTML 覆盖内容

OR

  • ????**insertAdjacentHTML() https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML** 不覆盖内容;灵活的;快速地

###???? 请参阅部分:Demo- 来源:#btn4 ????

var htmlString = `<button onclick="funcName(event, this)">4</button>`

document.querySelector('${selectorOfTarget}').insertAdjacentHTML("${position}", htmlString);
  • “目标选择器”:一个 CSS 字符串,表示我们希望在其中或周围插入 htmlString 的 DOM 元素。
  • "div"……:divid =“ID”class =“CLASS”>div>
  • "#ID“......:
    id="ID"类=“CLASS”>
  • ".CLASS"....:
    类=“类”>
  • #ID + ul....:
    id="ID"类=“CLASS”>
    ul>ul>
  • #ID + ul li.:
    id="ID"类=“CLASS”>
    ul><li>li>ul>

* ***"position":*** A string that determines where the htmlSting will be inseted in relation to the target element:
    <!--"beforebegin"-->
    <ul>
    <!--"afterbegin"-->
      <li>ITEM</li>
      <li>ITEM</li>
      <li>ITEM</li>
    <!--"beforeend"-->
    </ul>
    <!--"afterend"-->

* ***htmlString:*** A String that literally represents HTML. Instead of using String Literals, use **[Template Literals][4]**:

字符串字面量

    '<div id="'+ID+'" class="'+CLASS+'">+CONTENT+</div>'

模板文字

    `<div id="${ID}" class="${CLASS}">${CONTENT}</div>`

????(See section: **Event Handling** - list item: 2. **On-event Property** and section: **Demo** - source: `#btn1`.)
##Demo
var htmlString = `<button id='btn4' onclick='showHide(event)'>4</button>
<div class='content hide'>
  <h4>Dynamically Registered On Event Attribute by Parsing htmlString</h4>
  <pre><code>
document.querySelector('#btn3+div+hr').insertAdjacentHTML('afterend', htmlString);
</code></pre>
</div>
<hr>`;

function showHide(event) {
  var tgt = event.target;
  if (tgt.tagName === "BUTTON") {
    var code = tgt.nextElementSibling;
    code.classList.toggle('hide');
  }
  return false;
}

//#btn1
//On-Event Property
document.getElementById('btn1').onclick = showHide;

//#btn2
//EventListener
document.getElementById('btn2').addEventListener('click', showHide);

//#btn3
//Dynamically registered On event Attribute by setAttribute() method. 
document.getElementById('btn3').setAttribute('onclick', "showHide(event, this)");

//#btn4
//Dynamically Registered On Event Attribute by Parsing htmlString
document.querySelector('#btn3+div+hr').insertAdjacentHTML('afterend', htmlString);
* {
  margin: 0;
  padding: 0
}

button {
  padding: 2px 5px;
}

button+div {
  opacity: 1;
  transition: opacity 1s ease;
}
.content {
  margin: 0 0 20px 0
}
button+div.hide {
  opacity: 0;
  transition: 1s ease;
}
code {
  background: #000;
  color: lime;
}
<!--#btn0-->
<button id='btn0' onclick="showHide(event, this)">0</button>
<div class='content hide'>
  <h4>On-Event Attribute</h4>
  <pre><code>
&lt;button id='btn0' onclick="showHide(event, this)"&gt;On-Event Attribute&lt;/button&gt;
</code></pre>
</div>
<hr>

<!--#btn1-->
<button id="btn1">1</button>
<div class='content hide'>
  <h4>On-Event Property</h4>
  <pre><code>
document.getElementById('btn1').onclick = showHide;
</code></pre>
</div>
<hr>

<!--#btn2-->
<button id='btn2'>2</button>
<div class='content hide'>
  <h4>EventListener</h4>
  <pre><code>
document.getElementById('btn2').addEventListener('click', showHide);
</code></pre>
</div>
<hr>

<!--#btn3-->
<button id='btn3'><del>3</del></button>
<div class='content'>
  <h4>Dynamically Registered On Event Attribute by <code>setAttribute()</code> method <b>FAILED</b></h4>
  <pre><code>
<del>document.getElementById('btn3').setAttribute('onclick', 'showHide(event)');</del>
</code></pre>
</div>
<hr>

<!--#btn4 is dynamically created and will be inserted here-->
<!--Selector: '#btn3+div+hr' ||  Position: 'afterend'-->
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 setAttribute() 添加“onclick”函数 的相关文章

  • 标点符号加载“动画”,javascript?

    我正在寻找一种好方法来显示一些标点符号加载 动画 我想要的是这样的 This will display at second 1 Waiting for your input This will display at second 2 Wai
  • Google 文档 - 以编程方式将鼠标点击发送到大纲窗格中的项目

    在 Google 文档中 您可以打开大纲窗格并查看文档中的所有标题 您也可以单击标题 视图将滚动到标题 我的问题是如何使用 Chrome 扩展中的 JS 以编程方式模拟鼠标单击 以将视图滚动到所需的标题 我尝试了以下代码 但没有任何反应 u
  • 如何延迟 NavLink 的反应?

    Delay e gt e preventDefault setTimeout gt e unpreventDefault make this work 500 render
  • jQuery 单属性、带过滤器的多值选择器

    Images var boxlinks a href filter href png href gif href jpg href jpeg 有没有更有效的方法来使用 jQuery 中的过滤器选择单个属性的多个值 这里我尝试仅选择带有图像作
  • JavaScript 逻辑赋值是如何工作的?

    在 javascript 中 如果我们有一些代码 例如 var a one var b q a alert b 逻辑 OR 运算符会将 a 的值分配给 b 并且警报将为 一 这仅限于作业还是我们可以在任何地方使用它 似乎空字符串被视为与未定
  • jQuery - 拖动div css背景

    我希望能够在 div 内按住鼠标并移动它的背景 在谷歌上搜索了很多 没有找到我想要的 这是目标 显示的地图是要拖动的对象 http pontografico net pvt gamemap http pontografico net pvt
  • 无法读取setInterval(Hooks)中的最新状态变量[重复]

    这个问题在这里已经有答案了 我想这是因为 JS 的工作原理 但我想你不会在类中遇到这个问题 在此代码中 let open setOpen React useState false let counter setCounter React u
  • 在js中检测浏览器的最佳方法

    JavaScript 中有很多浏览器检测方法 据我所知 使用navigator userAgent或检测特征 例如XMLHttpRequest 等等 谁能告诉我哪种方法最好 最有效 如果你真的需要知道什么browser他们正在使用 你主要需
  • 有一个带有复选框的 jsTree,如何禁用所有复选框?

    我有一个动态构建的 jsTree 它允许用户选择他选择的任何节点 现在我试图使这棵树只读 以便其他用户可以看到信息而不改变它 我找到的所有示例都是关于禁用特定节点 我的问题是 有没有办法将树上的所有复选框定义为只读 正在使用的代码 jQue
  • 使用 jQuery 解析无效的 HTML,而不添加到 DOM?

    我正在开发一个使用 HTML 模板的 jQuery 插件 最终用户可以传入一个最简单级别的模板 如下所示
  • Material.Angular.io mat-autocomplete [displayWith] 函数更新范围变量

    我遇到了一个问题 我可以在实例化 mat autocomplete 的组件控制器中访问本地声明的变量 我面临的问题是局部变量被困在这个范围内 我无法更新它们 有关更新 mat autocomplete 范围变量的任何想法或想法 最终我要做的
  • 附加元素在 IE11 中不起作用

    在构造函数中我创建一个元素 var this legendElement this compileLegend 后来我想在事件监听器中使用它 var takeControl function this element empty this
  • 未处理的承诺拒绝:Zone.js 检测到 ZoneAwarePromise `(window|global).Promise` 已被覆盖

    我尝试将 Angular2 快速入门代码合并到我当前的 webpack 构建中 似乎有些东西正在覆盖zone js抛出此错误的承诺 根据我见过的大多数 stackoverflow 帖子 zone js文件需要在任何可能包含承诺的文件之后加载
  • backbone.js:视图中影响集合中不同模型的按钮

    我刚刚开始使用backbone js 到目前为止 我真的很喜欢它 我有这样的事情 ModelA ModelB ViewA ViewB ModelA 持有 ModelB 的集合 如何使用按钮构建模型 B 的视图 单击该按钮会更改集合中下一个
  • 如何修复带有单个道具的括号的 prettier 和 tslint 错误?

    我使用 prettier 和 tslint https github com alexjoverm tslint config prettier https github com alexjoverm tslint config prett
  • Skrollr 添加空白

    我已经尝试了一切 我在谷歌上阅读了 4 5 页试图找到适合我的修复程序 已经筋疲力尽了 即使我使用 skrollr 示例 我的问题仍然存在 不是说他们做错了什么 我知道我只是没有正确理解它 因此 我上传了一个演示 仅在移动设备上展示这个尴尬
  • 使用 Javascript 检测 Pepper (PPAPI) Flash

    我们使用的是专有的文档查看器 它与某些 Chrome 版本中的 Pepper 版本的 Flash 配合得不太好 所以我希望能够检测到它并重定向到不同格式的相同内容 由于这个版本似乎落后于 NPAPI 版本 所以我一直在使用闪光检测 http
  • 在 Javascript 中创建数组

    我对 javascript 不太熟悉 并且在用 javascript 制作 2d 或者也许我可能需要 3d 数组时遇到了一些麻烦 我目前需要收集 2 条信息 一个 ID 和一个值 因此我创建了以下内容 var myArray var id
  • 如何用时刻找到与给定时间最接近的时间?

    所以我有一个简单的代码 一个工作代码 它使用 moment 获取最接近给定时间的时间 Current time in millis const now moment 10 16 HH mm format x List of times co
  • 将 javascript 变量作为参数传递给 @url.Action()

    是否可以将javascript变量作为参数传递给 url Action 因为据我所知可能存在服务器和客户端问题 我的要求是我必须根据过滤器下载文件 并进行ajax调用不适用于下载文件 所以我对 url Action 进行了编码 但无法实现这

随机推荐