gpt4 book ai didi

如果我改变位置,Javascript标签不会运行

转载 作者:行者123 更新时间:2023-11-28 19:30:09 25 4
gpt4 key购买 nike

我有一个示例页面,在此页面中,js 插入了 body 标记之外,因此它不起作用。但如果你在正文结束标记之前编写脚本,那么它就会起作用。我不知道为什么会发生这种情况,其他脚本在不同的文件中运行良好。

示例代码:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>mouseover demo</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$( "div[class^=star]" )
.mouseover(function() {
$( this ).find( "span" ).text( "mouse Over" );
})
.mouseout(function() {
$( this ).find( "span" ).text( "mouse Out" );
});
</script>
</head>
<body>
<table><tr><td>
<div class="staroverout">
<span>move cursor to change text</span>
</div>
<br>
<div class="staroverout">
<span>move cursor to change text</span>
</div>
<br>
<div class="nstaroverout">
<span>move cursor to change text</span>
</div>
</td></tr></table>
</body>
</html>

最佳答案

这里的问题是,当您尝试选择 DOM 时,它没有加载。您必须使用 $(document).ready() 来确保在执行代码之前加载页面。

将代码包装如下:

$(document).ready(function () {
$( "div[class^=star]" )
.mouseover(function() {
$( this ).find( "span" ).text( "mouse Over" );
})
.mouseout(function() {
$( this ).find( "span" ).text( "mouse Out" );
});
}

关于如果我改变位置,Javascript标签不会运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26990625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com