[英]Javascript onclick function to change all instances of an element?
我正在嘗試在用戶單擊按鈕的地方構建某種東西,它會更改頁面上“ section”元素的所有實例的背景顏色。 當意識到無法立即更改多個部分的代碼時,我將其縮減為一個部分,但仍然無法正常工作。
這是我的代碼的簡化版本...
<section id="colorSection">
<div id="colorWrap" class="wrap">
<h1>Choose the color you'd like the demo to be in</h1>
<div id="colorSelector">
<button id="black" class="colorButton"></button>
<button id="white" class="colorButton"></button>
</div>
</div>
</section>
<script>
var colorSection = document.getElementById('colorSection');
var blackButton = document.getElementById('black');
var whiteButton = document.getElementById('white');
blackButton.onclick = function(){
colorWrap.style.backgroundColor = "#444;"
}
whiteButton.onclick = function(){
colorWrap.style.backgroundColor = "#efefef;"
}
</script>
我的邏輯告訴我...
我已經確定了一個部分並將其轉換為變量(“ colorWrap”)。
我已經確定了按鈕並將其轉換為變量。
我創建了一個單擊按鈕時觸發的函數,它使用colorWrap部分並相應地更改其背景顏色。
顯然,這沒有發生。 所以-有人可以告訴我在此示例中哪里出了問題,然后指出我的方向是:當按鈕處於按下狀態時,能夠影響元素的所有實例(而不是我由其ID標識的實例)點擊了嗎?
通過jQuery很容易實現。 您可以使用它的選擇器功能選擇所有想要的<section>
,並為其應用樣式:
對於一節
blackButton.onclick = function(){
$("section#colorSection").css("background", "#444");
}
whiteButton.onclick = function(){
$("section#colorSection").css("background", "#efefef");
}
對於所有部分
blackButton.onclick = function(){
$("section").css("background", "#444");
}
whiteButton.onclick = function(){
$("section").css("background", "#efefef");
}
只需使用jQuery的選擇器選擇所有<section>
(或者您的選擇器可能類似於section.ColorToggle
這樣您就可以指定要使用CSS類切換的部分)。
在上面,我使用ID選擇了特定的部分,因此只有彩色的部分。
您的包裝器變量是錯誤的(在onlick事件內部),十六進制顏色也應該沒有;
在末尾:
var colorSection = document.getElementById('colorSection'); var blackButton = document.getElementById('black'); var whiteButton = document.getElementById('white'); blackButton.onclick = function () { colorSection.style.backgroundColor = "#444" } whiteButton.onclick = function () { colorSection.style.backgroundColor = "#efefef" }
<section id="colorSection"> <div id="colorWrap" class="wrap"> <h1>Choose the color you'd like the demo to be in</h1> <div id="colorSelector"> <button id="black" class="colorButton">Black</button> <button id="white" class="colorButton">White</button> </div> </div> </section>
您尚未以任何方式設置colorWrap
var colorWrap = document.getElementById('colorWrap');
document.getElementById('red').onclick = function () { document.getElementById('mainSection').style.backgroundColor = "#ff8800" document.getElementById('mainSection').style.color = "#fff" } document.getElementById('white').onclick = function () { document.getElementById('mainSection').style.backgroundColor = "#efefef" document.getElementById('mainSection').style.color = "#333" }
<section id="mainSection"> <div id="colorWrap" class="wrap"> <h1>Choose the color you'd like the demo to be in</h1> </div> Try It Once </section> <div id="color"> <button id="red" class="colorButton">Add Color</button> <button id="white" class="colorButton">Remove Color</button> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.