我有两个可点击的div用于选择性别。现在我试图通过javascript将选择保存到变量以便以后使用它。我是javascript的新手,所以我很难找到一种方法。这是我的html(bootstrap):
<div class="col-md-6 col-md-offset-3 heading-center"></div>
<div class=" col-md-3 col-md-offset-2 div-gender" id="woman">
<a href="#seite2">
<img src="img/woman.png">
</a>
</div>
<div class=" col-md-3 col-md-offset-2 div-gender" id="man">
<a href="#seite2">
<img src="img/man.png">
</a>
</div>
修改: div使用css点击:
.div - gender a
{
display: block;
}
答案 0 :(得分:1)
var userGender; // will hold the gender
var genderDIV = document.getElementsByClassName('div-gender');
function storeGender(event){
event.preventDefault(); // Prevent default anchor behavior
userGender = this.id ; // Sets Gender to the clicked DIV ID
alert( userGender ); // Test only
}
// Assign click handler to all .div-gender
// The listener data callback will be our storeGender
// function that will capture the event and the 'this'
// reference to the clicked element (see fn above).
for(var i=0; i<genderDIV.length; i++){
genderDIV[i].addEventListener('click', storeGender, false);
}