jquery 代码在控制台上有效,但在脚本标签或附加的 js 文件中无效
The jquery code works on console but not in script tags or in attached js file
$(".filter-close").click(function(){
$(this).parent().remove();
});
此代码段在控制台中有效,但在脚本标记和附加的 js 文件中均无效。
可能在您调用此函数时filter-close
class 中不存在DOM 中的元素。我想您是在动态地向 DOM 添加元素。你是吗?
可能是在附加事件处理程序时 DOM 中不存在的问题。
尝试这样的事情:
$( document ).ready(function() {
// Handler for .ready() called.
$(".filter-close").click(function(){
$(this).parent().remove();
});
});
$.ready()(下面的link)确保它不会在呈现DOM之前尝试调用代码来添加处理程序,类似于OnLoad。
Documentation for JQuery .ready()
method
也存在潜在的库冲突(请参阅 @D4V1D 的回答作为示例),但我们不能肯定地说不知道控制台中出现了什么错误消息(如果有的话),最好是更多关于周围代码的信息。
请按 F12 并查看控制台 and/or 网络面板中打印的内容,或者 google "BrowserName dev console" 如果 F12 不执行任何操作。
但是,正如所说它在控制台中工作,所以我假设你的意思是开发控制台,它实际上只是一个时间问题,所以不太可能发生冲突(尽管页面上其他地方仍然可能有语法错误)
等待 DOM 调用您的事件处理程序时准备就绪:
jQuery(function($) { // this does the trick and also makes sure jQuery is not conflicting with another library
$(".filter-close").click(function(){
$(this).parent().remove();
});
});
When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code
$(".filter-close").click(function(){
$(this).parent().remove();
});
此代码段在控制台中有效,但在脚本标记和附加的 js 文件中均无效。
可能在您调用此函数时filter-close
class 中不存在DOM 中的元素。我想您是在动态地向 DOM 添加元素。你是吗?
可能是在附加事件处理程序时 DOM 中不存在的问题。
尝试这样的事情:
$( document ).ready(function() {
// Handler for .ready() called.
$(".filter-close").click(function(){
$(this).parent().remove();
});
});
$.ready()(下面的link)确保它不会在呈现DOM之前尝试调用代码来添加处理程序,类似于OnLoad。
Documentation for JQuery .ready()
method
也存在潜在的库冲突(请参阅 @D4V1D 的回答作为示例),但我们不能肯定地说不知道控制台中出现了什么错误消息(如果有的话),最好是更多关于周围代码的信息。
请按 F12 并查看控制台 and/or 网络面板中打印的内容,或者 google "BrowserName dev console" 如果 F12 不执行任何操作。
但是,正如所说它在控制台中工作,所以我假设你的意思是开发控制台,它实际上只是一个时间问题,所以不太可能发生冲突(尽管页面上其他地方仍然可能有语法错误)
等待 DOM 调用您的事件处理程序时准备就绪:
jQuery(function($) { // this does the trick and also makes sure jQuery is not conflicting with another library
$(".filter-close").click(function(){
$(this).parent().remove();
});
});
When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code