我正在尝试创建一个网站,用户可以在其中创建自己的社交网络按钮。 (我知道它已经完成,但主要是为了练习)。该网站的一部分将允许用户选择按钮的形状。这是 HTML:
<div class="design" id="shape">
<div class="shapeSelect square" id="square"></div>
<div class="shapeSelect rounded" id="rounded"></div>
<div class="shapeSelect circle" id="circle"></div>
</div>
我想做的是在单击 div 时添加一个事件监听器。单击后,类属性将更改为“选定”。当单击另一个时,第一个单击的将被清除,并选择下一个。就像单选按钮一样。
我熟悉 JavaScript,我的想法是这样的:
window.onload = function () {
'use strict';
document.getElementById("square").addEventListener('click', function (e) {//adds the event listener
divArray = document.getElementById("shape");//Here is my first issue: an array is not returned
if (!(document.getElementById("square").getAttribute("class") == "shapeSelect square selected")) {// checks to make sure its not already selected
for (i = 0, count = document.getElementById("shape").length; i < count; i++) {// if it isn't go through the array
divArray[i]// and this is where i also get stuck. I Can't figure out how i would return the class attribute to be class="shapeSelect circle" instead of class="shapeSelect circle selected"
};
}
}, false);
}
最佳答案
scdavis41 答案的更简单版本:
$(document).ready(function(){
$('#shape > .shapeSelect').click(function(){
$('#shape > .shapeSelect').removeClass('selected');
$(this).addClass('selected');
});
});
我还放置了一个选择器,其中包含控件的主 div id,以防您想在页面中多次放置此控件。
** 编辑 **
如果您绝对想使用 javascript 和 DOM,请尝试以下操作:
document.getElementById("square").addEventListener('click', function (e) {
var divArray = document.getElementById("shape").getElementsByTagName("div"); //Get all the div child element of the main div
for (i = 0, count = divArray.length; i < count; i++) {
if(divArray[i].getAttribute("class").indexOf("selected") !== -1) { //check if the selected class is contained in the attribute
divArray[i].setAttribute("class", divArray[i].getAttribute("class").replace("selected", "")); // clear the selected class from the attribute
}
};
document.getElementById("square").setAttribute("class", document.getElementById("square").getAttribute("class").concat(" selected")); //select the square
}, false);
关于javascript - 使用 DIV 创建我自己的类似单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17867895/