有没有办法在单个js文件中为特定页面URL调用特定javascript函数?
我有一个问题,我想知道如果打开了一个特定的页面URL,是否有方法调用一个特定的函数有没有办法在单个js文件中为特定页面URL调用特定javascript函数?,javascript,jquery,ajax,Javascript,Jquery,Ajax,我有一个问题,我想知道如果打开了一个特定的页面URL,是否有方法调用一个特定的函数 #莫代尔商店在http://myurl/liste-boutique.php #dep_modal正在运行http://myurl/index.php 现在,我在尝试打开#dep#u模式时出错,因为JS无法在同一页面上找到#shop#u模式,因此它不会在该页面下方执行 我认为AJAX可以帮助解决这个问题,否则我将不得不将代码拆分为2个JS文件,我不想这样做 const new_shop = $("#
- #莫代尔商店在http://myurl/liste-boutique.php
- #dep_modal正在运行http://myurl/index.php
const new_shop = $("#new_shop")[0];
const save_shop = $("#shop_form")[0];
const close_shop_modal = $("#close_shop_modal")[0];
const new_departement = $("#new_dep")[0];
const save_departement = $("#dep_form")[0];
const close_dep_modal = $("#close_dep_modal")[0];
// I want this to be called if the URL is http://my-URL/liste-boutique.php
new_shop.addEventListener('click', function(){
$("#shop_modal")[0].style.visibility = "visible";
})
// I want this to be called if the URL is http://my-URL/index.php
new_departement.addEventListener('click', function(){
$("#dep_modal")[0].style.visibility = "visible";
})
我需要问一个问题,但我不知道在这里要改变什么
再次感谢 您可以查看
window.location.href
。例如
if(window.location.href=='http://my-URL/liste-boutique.php') {
新建\u shop.addEventListener('单击',函数()){
$(“#商店模式”)[0].style.visibility=“可见”;
});
}
检查您要查找的元素是否在页面上,而不是检查url:
var $new_shop = $("#new_shop");
if ($new_shop.length > 0) {
var new_shop = $new_shop[0];
new_shop.addEventListener('click', function(){
$("#shop_modal")[0].style.visibility = "visible";
})
}
(为了清晰起见,我在$new\u shop
上使用了$
前缀来显示它是一个jquery对象)
或者,按原样使用代码:
var new_shop = $("#new_shop")[0];
if (new_shop != undefined) {
new_shop.addEventListener...
或者,如果使用jquery,则无需担心它,因为如果元素不存在,它将自动不应用:
$("#new_shop").click(() => { $("#shop_modal)").fadeIn(); });
是的,对不起,我编辑了它,谢谢你的信息:)谢谢你,我会试试这个