我有data-right-answer,可以保留正确的答案,如果正确的答案我应该更改边框颜色,否则我应该在输入值中输入正确的答案,我无法想象我应该如何使用属性来做
var btn = document.getElementById("myBtn");
btn.addEventListener("click", checkInputs);
var inputs = document.querySelectorAll("input");
function checkInputs(){
for( var i = 0; i < inputs.length; i++ ){
if( inputs[i].getAttribute("data-right-answer") == inputs[i].value ){
inputs[i].style.border = "1px solid green";
} else{
// inputs[i].value = getAttribute("data-right-answer");
}
}
}
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<button id="myBtn">Start</button>
答案 0 :(得分:1)
您忘记了在else条件下获取属性值。
inputs[i].value = inputs[i].getAttribute("data-right-answer");
var btn = document.getElementById("myBtn");
btn.addEventListener("click", checkInputs);
var inputs = document.querySelectorAll("input");
function checkInputs(){
for( var i = 0; i < inputs.length; i++ ){
if( inputs[i].getAttribute("data-right-answer") == inputs[i].value ){
inputs[i].style.border = "1px solid green";
} else{
inputs[i].value = inputs[i].getAttribute("data-right-answer");
}
}
}
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<button id="myBtn">Start</button>
答案 1 :(得分:0)
inputs [i] .dataset.rightAnswer =>这将捕获“ data-”属性的正确答案。 :D
var btn = document.getElementById("myBtn");
btn.addEventListener("click", checkInputs);
var inputs = document.querySelectorAll("input");
function checkInputs(){
for( var i = 0; i < inputs.length; i++ ){
if( inputs[i].dataset.rightAnswer == inputs[i].value ){
inputs[i].style.border = "1px solid green";
} else{
inputs[i].value = inputs[i].dataset.rightAnswer;
}
}
}
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<button id="myBtn">Start</button>
答案 2 :(得分:0)
$('#myBtn').click(function(){
$('input').each(function(){
if($(this).attr('data-right-answer')==$(this).val())
{
$(this).css('border','1px solid green')
}
else{
if($(this).val()!='')
{
$(this).val($(this).attr('data-right-answer'))
}
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<input type="text" data-right-answer="Lolik">
<button id="myBtn">Start</button>