我正在尝试使用onclick调用一个函数,但此函数已经在通过onclick调用的另一个函数中。
实际上,我想继续这样做6-7次。
代码可能有助于减少混淆:
HTML+JS:
{
<body>
<script type="text/javascript">
function abc()
{
document.getElementById("first").className='disc';
document.getElementById("first").onClick="def();";
}
function def()
{
document.getElementById("first").className='disco';
}
</script>
<input type="button" value="Change Color of this text" id="first" class="" onclick="abc();">
</body>
}CSS:
.disc
{
color: red;
}
.disco
{
color: yellow;
}我想在每次用户点击按钮时改变文本的颜色。那么问题出在哪里呢?它只是变成红色,但当我再次点击它时,它不会变成黄色。
发布于 2014-07-02 11:16:09
我认为根据你在评论中的要求,这应该适用于你:
Javascript
function abc(){
if(document.getElementById("first").className == "" || document.getElementById("first").className == "disco"){
document.getElementById("first").className = "disc";
}
else if(document.getElementById("first").className=="disc"){
document.getElementById("first").className="disco";
}
}您不需要更改HTML和css中的任何内容。
发布于 2014-07-02 11:16:16
而不是将函数从abc()更改为def(),我不确定您是否可以这样做。为什么不使用1个函数并检查当前的className,如下面的代码所示:
function abc()
{
if(document.getElementById("first").className == "disco" || document.getElementById("first").className == "") //change from red to yellow
document.getElementById("first").className="disc";
else //change from yellow to red
document.getElementById("first").className="disco";
}发布于 2014-07-02 11:16:42
var first = document.getElementById("first"), counter = 0;
first.addEventListener('click', function () {
first.className = (counter % 2) ? 'disc' : 'disco';
counter +=1;
});修复代码和更可靠的解决方案。
https://stackoverflow.com/questions/24522194
复制相似问题