Jquery,当包含特定id的页面触发Jquery函数时,有没有办法?
我的目标是在页面包含特定id时触发jquery函数Jquery,当包含特定id的页面触发Jquery函数时,有没有办法?,jquery,Jquery,我的目标是在页面包含特定id时触发jquery函数 或者jquery在读取最后2个url段时是否有触发的方式 问题1 HTML <input type="hidden" id="furniture_features_03"> 问题2 if the page url with /furniture/bills/ then the jquery will trigger 例如,当我加载此url时:https://stackoverflow.com/furniture/bill
<input type="hidden" id="furniture_features_03">
问题2
if the page url with /furniture/bills/
then the jquery will trigger
例如,当我加载此url时:
https://stackoverflow.com/furniture/bills
,然后页面将自动弹出一条警告消息以检查它是否存在,使用长度,然后使用代码(下面是jquery或纯javascript):
jquery
$( "#furniture_features_03" ).function() {
alert( "furniture_features_03 is in this page" );
});
$(document).ready(function(){
if($( "#furniture_features_03").length > 0){
alert( "furniture_features_03 is in this page" );
}
});
普通javascript:
if(document.getElementById("furniture_features_03").length > 0){
alert( "furniture_features_03 is in this page" );
}
if(location.href.indexOf("/furniture/bills/") > -1){
alert( "furniture_features_03 is in this page" );
}
检查url:
if(document.getElementById("furniture_features_03").length > 0){
alert( "furniture_features_03 is in this page" );
}
if(location.href.indexOf("/furniture/bills/") > -1){
alert( "furniture_features_03 is in this page" );
}
试试这个..
$(document).ready(function(){
if($("#furniture_features_03").length > 0 || window.location.href.includes('/furniture/bills/')){
alert( "furniture_features_03 is in this page" );
}
});
不可以。但是,您可以在特定时间运行代码,并使用该代码确定元素是否存在。例如,在页面加载、文档准备就绪、点击事件之后、ajax之后,等等,我想知道如何做到这一点?我的意思是,我给出的四个选项中的任何一个都会起作用。哇,这真的很有效……而且是直截了当的回答!但在我作出任何可接受的决定之前,我希望看到另一种方法answer@LearnProgramming我更新了我的答案,包括3个不同的选项,测试了所有选项,效果很好!但是如果url有额外的参数,如/furniture/bills/12,该怎么办?在
中检查url
部分?是否可以忽略该参数,因为我只关注前两个段,即/furniture/bills
onlyIndexOf
实际上搜索整个字符串中的“搜索字符串”因此URL可能有100个字符长,这其实并不重要。我在使用代码时出错。错误:window.location.href.contains不是一个函数您不应该得到该错误,但您可以尝试将“window.location.href.contains('/furniture/bills/')”替换为“(window.location.href.indexOf(“/furniture/bills/”)>-1)“应该是“.includes()”,而不是“.contains()”(我经常犯同样的错误)感谢大家的建议。我忘了contains不是所有浏览器都支持的