서로 다른 색상에 대해 두 개의 버튼을 사용하여 표 셀 (td)의 배경색을 변경하려면 어떻게해야합니까?

릴리아

내 HTML 파일 :

<!DOCTYPE html>
<html>
<head>
    <title>Wolf and Rabbit Game</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="wolf&rabbit_game.css">
    <script src="wolf&rabbit_game.js"></script>
</head>
<body>
<table>
    <tr>
        <td id="tableCell"></td>
    </tr>
</table>
<input id="button1" type="button" value="I'm red" onclick="setColorRed">
<input id="button2" type="button" value="I'm green" onclick="setColorGreen">
</body>
</html>

내 CSS 파일 : table {text-align : center; 여백 : 자동; }

td{
    border: 1px black solid;
    width: 25px;
    height: 25px;
}

#button1,#button2{
    text-align: center;
    margin-top: 20px;
    font-size: 1em;
    font-family: Myriad Pro;
    font-weight: semibold;
    color: white;
    border-radius: 15px;
    padding: 1%;
}

#button1{
    background: red;
}

#button2{
    background: green;
}

body{
    text-align: center;
}

img{
    width: 25px;
    height: auto;
}

내 JavaScript 파일 :

function setColor(){
  if ("#button1").click {
    document.getElementById("#tableCell").style.backgroundColor="red";
  };
  if ("#button2").click {
    document.getElementById("#tableCell").style.backgroundColor="green";
  };
};
Nirbhay Kundan

이 JS Fiddle 확인

JsFiddle 링크

두 개의 다른 버튼에 대해 두 가지 다른 메서드를 호출 할 필요가 없습니다. 색상 매개 변수를 받아들이고 원하는 요소의 색상을 변경하는 단일 메서드이면 충분합니다.

이와 같이 코드를 수정하고 자바 스크립트 코드가 버튼 마크 업 앞에 오도록해야합니다.

<script>
function setColor(color){  
    document.getElementById("tableCell").style.backgroundColor=color;
};
</script>

<table>
    <tr>
        <td id="tableCell">test</td>
    </tr>
</table>
<input id="button1" type="button" value="I'm red" onclick="setColor('red')">
<input id="button2" type="button" value="I'm green" onclick="setColor('green')">

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관