我有一个脚本,由"hello world“和"hello”和"world“组成,有两种不同的CSS样式。
我想点击他们中的任何一个,他们就会交换他们的风格。例如,我点击"hello“,它会与"world”交换样式。下面是我的代码。
我不能把它拿去交换。我该怎么改正呢?
<html>
<head>
<style>
#today{
font-weight: bold;
color: red;
}
#normal{
font-weight: normal;
color: green;
}
</style>
<script>
old="old";
function set(in){
var e = document.getElementsByName(old);
for(ii=0;ii<e.length; ii++)
{
var obj = document.getElementsByName(old).item(ii);
obj.id="normal";
}
old=in;
var e = document.getElementsByName(old);
for(ii=0;ii<e.length; ii++)
{
var obj = document.getElementsByName(old).item(ii);
obj.id="today";
}
}
</script>
</head>
<body>
<table>
<tr>
<td id="normal" name="new" onclick="set('new')">Hello</td>
<td id="today" name="old" onclick="set('old')">World</td>
</tr>
</table>
</body>
</html>发布于 2011-10-29 19:17:08
您在这里有一些问题。首先,在onclick处理程序中,它必须是"javascript:set“,而不仅仅是"set”。其次,您有一个名为"in“的参数,它是一个Javascript关键字。将它的所有引用更改为"inv“。如果你这样做了,你的代码就会正常工作。试试看。
除此之外,我建议您在Firefox中工作,并获得Firebug插件,这样您就可以打开控制台。它将显示这些类型的错误。
发布于 2011-10-29 19:29:54
任何时候,只有一个元素可以使用ID进行注释。因此,您应该使用类而不是ID来注释您的元素。此外,请确保包含一个doctype。
更正后的代码的:
<!DOCTYPE html>
<html>
<head>
<style>
.today{
font-weight: bold;
color: red;
}
.normal{
font-weight: normal;
color: green;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
var els = document.querySelectorAll('.normal,.today');
for (var i = 0;i < els.length;i++) {
els[i].addEventListener('click', function () {
var els = document.querySelectorAll('.normal,.today');
for (var i = 0;i < els.length;i++) {
var currentClass = els[i].getAttribute('class');
var newClass = currentClass == 'today' ? 'normal' : 'today';
els[i].setAttribute('class', newClass);
}
}, false);
}
}, false);
</script>
</head>
<body>
<table>
<tr>
<td class="normal">Hello</td>
<td class="today">World</td>
</tr>
</table>
</body>
</html>当然,使用jQuery ()编写要容易得多:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script>
$(function() {
$('.normal,.today').click(function() {
$('.normal,.today').each(function(i, el) {
var $el = $(el);
if ($el.hasClass('today')) {
$el.removeClass('today');
$el.addClass('normal');
} else {
$el.removeClass('normal');
$el.addClass('today');
}
});
});
});
</script>https://stackoverflow.com/questions/7938497
复制相似问题