包含的文件之间的Javascript事件委托

Javascript event delegation between included files

本文关键字:事件 之间 文件 包含 Javascript      更新时间:2023-09-26

我有Index.asp

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!--#include file="blocks/header.asp"-->
<!--#include file="blocks/bottom.asp"-->
<!--#include file="blocks/footer.asp"-->
</body>
</html>

块/header.asp

<div class="hideMeIamHeader"></div>

块/bottom.asp

<div class="hideMeIambottom"></div>

块/footer.asp

<div class="hideMeIamfooter"></div>
<button id="Hideheader">Hide Header</button>
<button id="Hidebottom">Hide bottom</button>
<button id="Hidefooter">Hide footer</button>
<script>
$(function() {
$('#Hideheader').on('click',function(){$('.hideMeIamHeader').hide();});
$('#Hidebottom').on('click',function(){$('.hideMeIambottom').hide();});
$('#Hidefooter').on('click',function(){$('.hideMeIamfooter').hide();});
});
</script>

如何使这个例子工作?我不能从footer.asp访问.hideMeIamHeader.hideMeIambottom

更新(解决)

所以index。asp必须像

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<!--#include file="blocks/header.asp"-->
<!--#include file="blocks/bottom.asp"-->
<!--#include file="blocks/footer.asp"-->
<script>
$(function() {
$('#Hideheader').on('click',function(){$('.hideMeIamHeader').hide();});
$('#Hidebottom').on('click',function(){$('.hideMeIambottom').hide();});
$('#Hidefooter').on('click',function(){$('.hideMeIamfooter').hide();});
});
</script>
</body>
</html>

最可能的情况是,在设置单击处理程序时,这些项还不存在于DOM中。你可以使用jQuery的ready()函数来纠正这个问题:

$(document).ready(function() {
    $('#Hideheader').on('click',function(){$('.hideMeIamHeader').hide();});
    $('#Hidebottom').on('click',function(){$('.hideMeIambottom').hide();});
    $('#Hidefooter').on('click',function(){$('.hideMeIamfooter').hide();});
});

jQuery文档:https://api.jquery.com/ready/

你的代码应该在DOM准备好后执行,

$(document).ready( function(){
    //Your code goes here
    $('#Hideheader').on('click',function(){$('.hideMeIamHeader').hide();});
    $('#Hidebottom').on('click',function(){$('.hideMeIambottom').hide();});
    $('#Hidefooter').on('click',function(){$('.hideMeIamfooter').hide();});
});

更多说明:你的代码是在文件被加载时执行的,而不是当整个页面被加载时,所以当Javascript页面被加载时,实际上页面和DOM元素并没有创建,所以jquery无法找到元素。

所以首先你需要加载所有的DOM内容,然后你要处理DOM元素,所以你的代码应该总是执行一旦DOM准备好了…