繁体   English   中英

JavaScript-如果选中了单选按钮,请更改背景色

[英]JavaScript - If radio button is checked, change background color

我对JavaScript相当陌生,在使用jQuery之前我想学习其中的一些内容,因此jQuery在这里是不可取的。

我有一个可以写文章的表格,并且我已经启动并运行了所有程序,并且效果很好。 图像选择器本身可以工作,但是它是我要固定的外观,因此我不必查看图像下方的难看的单选按钮,因此单选按钮将被删除,而是将图像的背景变为红色。或其他一些明显的颜色。

显示图像的代码是这样的,除了onlclick之外,它可以工作:

$dir = 'img/uploads/';

$images = glob($dir.'*.jpg');

$numPics = count($images) / 2 - 1;

for($i = 0; $i<=$numPics; $i++){

    if(strpos($images[$i], 'large')){

?>

<td>

    <label for="selectImage<?=$i; ?>">
        <img src="<?=$images[$i];?>" alt="<?=$images[$i]; ?>" width="250" id="imageLabel<?=$i; ?>">
    </label>

    <input type="radio" name="img" value="<?=$images[$i]; ?>" role="button" id="selectImage<?=$i; ?>" onclick="changeBackground('imageLabel<?=$i; ?>', 'selectImage<?=$i; ?>')">

</td>
<?php

    if($i == 3){

        echo "</tr>";

    }

   }

}

JavaScript是这样的:

function changeBackground(id, id2){

    if(document.getElementById(id2).checked == true;) {

        document.getElementById(id).style.backgroundColor = 'red';

    }

}

我想要的是,当我选中单选按钮时,图像上的背景图像会更改颜色,而当我检查另一幅图像时,它应该更改该图像上的背景颜色。 知道我该怎么做吗? 单选按钮将显示:无; 没问题。

任何帮助表示赞赏。

应该这样做:

function changeBackground(id, id2){

  if(document.getElementById(id2).checked) {

    document.getElementById(id).style.backgroundColor = 'red';

  }
}

您的状况中有分号,这会破坏整个过程。

实际上,您需要使用ZERO JavaScript来实现。

 input[type="radio"] { display: none; } input[type="radio"] + label { background-color: yellow; } input[type="radio"]:checked + label { background-color: lime; } 
 <input type="radio" name="r" id="r1"><label for="r1">One</label> <input type="radio" name="r" id="r2"><label for="r2">Two</label> <input type="radio" name="r" id="r3"><label for="r3">Three</label> <input type="radio" name="r" id="r4"><label for="r4">Four</label> 

对于您的问题,如果您在开发人员工具中打开JavaScript控制台,则会看到错误消息Uncaught SyntaxError: Unexpected token ; 或类似的东西,它指向if语句中随机放置的分号。 代码的下一个问题是,当未选中该复选框时,您不会将颜色切换回原来的颜色,因此,如果用户选择其他选项,则该选项仍将为绿色。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM