我想更改与radiobutton id =“male”相关联的标签文本。我已尝试过各种方法来做到这一点,但我不能让它发挥作用。我想更改与单选按钮关联的标签中的文字“男性”。
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
<input type="button" value="Submit" onclick = test()>
<script>
function test()
{
var r = document.getElementById("male");
r.nextSibling.data = "adaS";
// r.nextSibling.nodeValue = "adaS"; // have tried all these ways
// r.childNodes[0].value= "adaS";
// r.childNodes[0].innerHTML= "adaS";
// r.parentNode.childNodes[1].innerHTML= "adaS";
}
</script>
请建议一些改变标签中“男性”字样的工作方式。
答案 0 :(得分:1)
您可以使用
var r = document.getElementsByTagName("label")
选择页面中的所有标签元素,然后使用
r[0].innerHTML ="new text"
选择第一个标签并将文本设置为&#34;下一个文本&#34;在你的test()函数中
答案 1 :(得分:0)
我尝试使用上面的想法来获得一个有效的例子,并遇到了一些问题。所以我在另一个帖子中寻求帮助,@ KrishCdbry非常友好地解决了这个问题。发布的问题位于javascript - How to dynamically change information displayed by radio button?以下是Krish更改的工作示例
<html>
<form name="myform" onsubmit="OnSubmitForm();">
<input type="radio" id = 'first' name="operation" value="1"
checked> <label for="alsoFirst"> Answer 1 </label>
<input type="radio" id = 'second' name="operation" value="2">
<label for="alsoSecond">Answer 2</label>
<p>
<input type="submit" name="submit" value="save">
</p>
</form>
<script type="text/javascript">
document.addEventListener('readystatechange', function() {
// Seems like a GOOD PRACTICE - keeps me from getting type error I was getting
// https://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object
if (document.readyState === "complete") {
init();
}
});
function init() {
console.log ("expect to change -Answer 1- displayed by first button to word junk");
// this works
var label = document.getElementsByTagName('label') [0];
// this does not work
label.innerHTML = 'junk';
}
//http://www.javascript-coder.com/html-form/html-form-action.phtml
function OnSubmitForm()
{
if(document.getElementById('first').checked == true)
{
alert ( "You have selected the first answer" );
}
else
if(document.getElementById('second').checked == true)
{
alert ( "You have selected the SECOND answer" );
}
return false;
}
/*
<input type="radio" name="sex" id="male" value="male">
<label for="male">Male</label>
</input>
var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
*/
//https://stackoverflow.com/questions/32292962/javascript-how-to-change-radio-button-label-text
</script>
</html>
答案 2 :(得分:-1)
使用jQuery,var input = document.getElementById('male');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';
普通JS:
var label = document.getElementById('male').getElementsByTagName('label')[0];
label.innerHTML = 'New Text;
也可以将它们连在一起:
/Library/Frameworks/SDL2.framework