【发布时间】:2024-01-08 22:14:01
【问题描述】:
我已经制作了一个 jquery 函数,假设要执行 3 个步骤
- 加载它应该替换所有链接文件的属性
- 点击时应将子页面加载到 $("#content")
- 它应该再次重新触发将再次替换所有链接的功能
以下代码可以工作到 2 步,但不会触发第三步,这应该再次替换所有 url 我认为它也应该替换加载页面的链接?
$(document).ready(function(){
var base_url = "http://localhost/dolphin/";
$("a").each(function(e){
if(this.href == "javascript:void(0)" ||
this.href == base_url ||
this.href == base_url + "index.php" ||
this.href == "javascript:void(0);" ||
this.href == "javascript:%20void(0)") {
}else{
page = 'Javascript:LoadPage(\''+ this.href + '\')';
this.setAttribute('onclick',page);
this.setAttribute('href', '#');
}
});
});
function LoadPage(url){
$("#contentarea").load(url, function() {
//after loading it should call redoIt() but it doesnt.
redoIt();
});
}
function redoIt(){
var base_url = "http://localhost/dolphin/";
$("a").each(function(e){
if(this.href == "javascript:void(0)" ||
this.href == base_url + "index.php" ||
this.href == "javascript:void(0);" ||
this.href == "javascript:%20void(0)") {
}else{
page = 'Javascript:LoadPage(\''+ this.href + '\')';
this.setAttribute('onclick',page);
this.setAttribute('href', '#');
}
});
}
【问题讨论】:
-
你怎么知道
redoIt()没有被呼叫?你在里面放了断点吗?还是开头的console.log()声明?错误控制台中是否有任何 javascript 错误?你确定LoadPage()被调用了吗? -
你选择链接的方式实在是太可怕了......很久很久没有看到如此可怕的 jQuery 误用了。
-
我在 redoIt() 中添加了 alert(this.href) 但没有回复
-
@ThiefMaster 你能告诉我如何做得更好吗?而不是评论?
-
使用类名并按该类选择。要绑定点击事件,请使用
$(this).click(function(e) { e.preventDefault(); /* your code here */ });避免javascript:urls