【发布时间】:2017-07-17 10:49:15
【问题描述】:
我有一个文件“includes.html”,我在其中使用 Javascript 从外部文件“includesecondfile.html”中包含 HTML。
including.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>My First Document</title>
<link rel="stylesheet" type="text/css" href="including.css" />
<script type="text/javascript"src="http://ajax.aspnetcdn.com/ajax/jQuery /jquery-1.8.1.min.js"></script>
<meta charset="UTF-8">
</head>
<body>
<h1>My Web Page, I'm H1</h1>
<p>First P element. Welcome to my web page. Here you'll find all sorts of information about me.</p>
<h2>My Books second H2 element</h2>
<div id="menu"> </div>
<p>You can find information on my books here as well.</p>
<script>
$(function(){
$('#menu').load('includesecondfile.html');
});
</script>
<script>
$(function(){
$("h1").mouseenter(
function(){
$('h1').css('background-color', 'yellow');
}
);
$("h1").mouseleave(
function(){
$('h1').css('background-color', 'white');
}
);
});
</script>
</body>
</html>
下面是includesecondfile.html的内容
<hr>
<h1>Second file H1 element</h1>
<p>Here it is yo man secon paragraph element</p>
<h2>Second H2 element</h2>
<hr>
当我在浏览器中查看时,includesecondfile.html 中的元素正确显示,h1、h2 和 p 都正确显示。 当我将鼠标悬停在 include.html 中的 H1 元素上时,第二段 javascript 起作用,但当我将鼠标悬停在从 includesecondfile.html 导入的 H1 元素上时,则不起作用。奇怪的是,这两个文件的 h1 上的 CSS 都受到了影响。即,当我将鼠标悬停在主文件中的 h1 元素上时,两个 h1 的背景都变黄,但当我将鼠标悬停在包含文件中的 h1 元素上时,两个背景都不会变黄。 当我将鼠标悬停在包含文件的 h1 元素上时,如何使背景变为黄色?
【问题讨论】:
-
看起来额外的 HTML 是异步加载的,所以事件处理程序在加载之前绑定了 。对此有修复,但是,您为什么不在 CSS 中更改悬停颜色?你不需要 JS。
-
谢谢 nnnnnn,正如你所说。我将 JS 移至 includesecondfile.html 并且一切正常。我写这篇文章只是为了了解 JS,所以上面只是一些测试文件。
标签: javascript include mouseenter