2017-04-16 50 views
1

我怎麼能拒絕一個元素是這樣的:造型元素作爲選擇的onclick

<a href="#" class="select" id="select">Element1</a> 
<a href="#" class="select" id="select">Element2</a> 
<a href="#" class="select" id="select">Element3</a> 

要像選擇按鈕,例如,其正常的樣子是

.select { 
    border: 1px solid red; 
} 

但如果我點擊他們中的一個元素,它變成是

.select { 
    background-color: red; 
} 

但我想在這裏學習的伎倆,我怎樣才能使它只有一個元素是能夠擁有樣式,就像一個單選按鈕一樣,只有一個按鈕具有選定的樣式,如果我點擊另一個按鈕,樣式將從前一個樣式中移除並置於單擊樣式上,只有在可能的情況下才使用JavaScript和CSS

+0

作爲一個側面說明不使用多個ID與同值。 –

+0

@OusmaneMahyDiaw ID不用於類的相同方式嗎? –

+0

如果這裏的意圖只是給它應用到的標籤賦予意義,那麼即使它不被推薦也沒問題,但是,如果在JavaScript中只有第一個元素具有相同的id,那麼只有第一個元素將被定位或使用CSS。簡單地說,ID應該是獨一無二的。 –

回答

2

//get all buttons 
 
var btns = document.getElementsByClassName("select"); 
 

 
function clicker() { 
 
    //loop through all buttons 
 
    for (y = 0; y < btns.length; ++y) { 
 
    //if button is not the current button remove the background class 
 
    if (btns[y].classList.contains && btns[y] != this) { 
 
     btns[y].classList.remove("colorize") 
 
    } //end if 
 
    //add background class to current button 
 
    this.classList.add("colorize"); 
 
    } 
 
} 
 
//add an event handler to all buttons 
 
for (x = 0; x < btns.length; ++x) { 
 
    btns[x].addEventListener("click", clicker) 
 
}
.select { 
 
    border: 1px solid red; 
 
} 
 

 
.colorize { 
 
    background-color: red; 
 
}
<a href="#" class="select">Element1</a> 
 
<a href="#" class="select">Element2</a> 
 
<a href="#" class="select">Element3</a>

+0

這種方法似乎不是很複雜,如果我誠實,它不使用jQuery,但我猜。然而,OP包含了jQuery標籤,因此我假定他使用它, – Xander

+0

True,但他說「僅在可能的情況下使用JavaScript和CSS」 – repzero

+0

是的我的壞,沒有看到 – Xander

1

你可以試試這個: - 首先,從所有的鏈接刪除選擇類,然後選擇到點擊鏈接(使用jQuery)添加。

HTML

<a href="#" class="select" id="select1">Element1</a> 
<a href="#" class="select" id="select2">Element2</a> 
<a href="#" class="select" id="select3">Element3</a> 

CSS

.select { 
    border: 1px solid red; 
} 
.selected { 
    background-color: red; 
} 

jQuery的

$(document).ready(function(){ 
    $('.select').click(function(){ 
     $('.select').removeClass('selected'); 
     $(this).addClass('selected'); 
    }); 
}) 

Live Example

+0

親愛的,下來投票者也可以自由添加評論。這將更加欣賞。謝謝。 –

+0

我真的不知道爲什麼這樣投票,這是最簡單的方法來解釋如何在jQuery中做到這一點,我真的想選擇你的答案和@repzero答案。 –

+0

如果它得到了千分之一票,這並不重要。我很高興至少可以幫助你。 :) –

-1

可以使用JavaScript和addClass()方法做到這一點很容易。

首先,不要對多個元素使用相同的ID。

HTML:

<a href="#" class="select" id="Element1">Element1</a> 
<a href="#" class="select" id="Element2">Element2</a> 
<a href="#" class="select" id="Element3">Element3</a> 

CSS:

.select { 
    border: 1px solid red; 
} 

.clicked { 
    background-color: red; 
} 

的JavaScript:

$(document).ready(function() { 

$(".select").click(function() { 
    $(".select").addClass("clicked"); 
}); 

}); 

注意此方法使用jQuery的