[英]Why isnt my javascript working?
我的所有代码似乎都可以正常工作,除了我的JavaScript之外,我是否做错了什么? 谢谢林只是一个初学者!
当鼠标悬停在“标签”标签上时,我正在尝试更改背景,但不会这样做吗? 到底是怎么回事?
HTML:
<html>
<head>
<script language="JavaScript" type="text/javascript">
// This changes color on mouseover, leaves existing color box.
$('.tab-item').mouseover(function() {
$(this).addClass("tab-mouseover");
}).mouseout(function() {
$(this).removeClass("tab-mouseover");
});
// This changes color when clicked, removed old color box.
$('.tab-item').click(function() {
$('.tab-item').removeClass("tab-selected");
$(this).addClass("tab-selected");
});-->
</script>
<link href="arg.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="tab-item tab-selected" id="search-box">
Search
</div>
<div class="tab-item" id="tag-box">
Tags
</div>
</body>
</html>
CSS:
.tab-item {
-moz-border-radius: 10px;
border-radius: 10px;
font: 14px helvetica;
color: #000;
height: 20px;
float: left;
margin: 5px 5px 5px 5px;
padding: 5px 5px 5px 5px;
position: relative;
width: 75px;
}
.tab-mouseover {
background: #bdbdbd;
}
.tab-selected {
background: #c0c0c0;
}
谢谢!
詹姆士
您正在使用jQuery,但尚未包含它。 您还需要将您的jquery代码放入jquery ready事件中:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
// This changes color on mouseover, leaves existing color box.
$(function(){
$('.tab-item').mouseover(function() {
$(this).addClass("tab-mouseover");
}).mouseout(function() {
$(this).removeClass("tab-mouseover");
});
// This changes color when clicked, removed old color box.
$('.tab-item').click(function() {
$('.tab-item').removeClass("tab-selected");
$(this).addClass("tab-selected");
});
});
-->
</script>
您尚未在此处添加您的库(我认为是jQuery)作为源。 像这样添加:
<script src='http://foo.com/bar/library.js'></script>
如果确实使用jQuery,则可以直接添加以下代码以使其工作:
<script src='http://code.jquery.com/jquery-1.6.4.js'></script>
请注意,以上内容意味着您取决于jQuery网站的可用性,而不是您自己的网站。
根据James对此的评论,是的,您可以完全删除jQuery,但是我建议您自己学习JavaScript,而不是从网站上复制代码。 如果要在鼠标悬停时更改字段的背景色,请使用如下代码:
<div onmouseover="this.style.backgroundColor='#bdbdbd';" onmouseout="this.style.backgroundColor='white';">Search</div>
要么
<div onmouseover='this.className="tab-mouseover"' onmouseout='this.className=""'>Search</div>
或不使用JavaScript而仅使用简单的CSS:
<style>
.tab-mouseover:hover{
background: #bdbdbd;
}
</style>
<div class='tab-mouseover'>Search</div>
我无法回答后一部分,因为我不理解删除然后将相同的类添加到元素onclick的用法。
好吧,首先,您没有在代码中包含指向jQuery库的链接。 结果,无论放置在哪里,您的代码都将无法工作。
其次,由于您的代码位于文档head
的script
元素中,因此它将在呈现文档body
之前执行。 您需要将其放入
$(document).ready(function() {
/*
* Your code here
*/
});
块。
尝试这个:
$('.tab-item').hover(
function() {
$(this).addClass('tab-mouseover');
},
function() {
$(this).removeClass('tab-mouseover');
}
);
$('.tab-item').click(function() {
$('.tab-selected').removeClass('tab-selected');
$(this).addClass('tab-selected');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.