简体   繁体   English

内联事件处理程序与单独的JavaScript文件中的事件处理程序混淆

[英]Inline Event handler messing with event handler in separate JavaScript file

Could something in the code of an inline event handler like in the HTML markup affect some code or prevent it from firing code in a JavaScript file that is later called. 内联事件处理程序的代码中的某些内容(例如HTML标记)可能会影响某些代码或阻止其触发后来调用的JavaScript文件中的代码。 Suppose the JavaScript file contained something like this. 假设JavaScript文件包含这样的内容。

$(a).click(function() {
//some code
 }

someJavaScriptCode isn't meant to be valid JavaScript syntax. someJavaScriptCode并非有效的JavaScript语法。 It is generated by the PrimeFaces library. 它由PrimeFaces库生成。

My event handler in the JavaScript file works once, but any subsequent clicks after that; 我在JavaScript文件中的事件处理程序可以运行一次,但是此后的任何后续单击都可以; it doesn't fire. 它不会开火。 The code in the inline event handler still works however. 但是,内联事件处理程序中的代码仍然有效。 I didn't make up the inline code; 我没有编写内联代码; it was web application's UI library doing that. 那是Web应用程序的UI库。 I'm just wondering how I can make the code above still work. 我只是想知道如何使上面的代码仍然有效。

If your inline code has an error in it, and it is executed before the JavaScript in your javascript file, then it will halt javascript execution which would prevent your external file javascript from running. 如果您的内联代码中有错误,并且在您的javascript文件中的JavaScript之前执行了该代码,则它将暂停javascript的执行,这将阻止您的外部文件javascript运行。

I hope this helps. 我希望这有帮助。

Are you using a framework that re-renders your DOM? 您是否正在使用重新呈现DOM的框架? It seams that when you click the element, it is replaced and it looses the event that is applied in your JavaScript file. 它表明,当您单击该元素时,该元素将被替换并失去在JavaScript文件中应用的事件。

If that is the case, place your event on a parent that is not being re-rendered, and target the element this way: 如果是这种情况,请将您的事件放置在未重新呈现的父对象上,并以此方式定位元素:

$( parent ).on( 'click', 'a', function (e) {})

The second argument in the "on" method will target any selector and apply the click even, even if the content of the parent is refreshed. “ on”方法中的第二个参数将以任何选择器为目标,即使刷新父级的内容也将应用单击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM