的HTML輸入標記得到相關的文本我有一個像下面如何在類型複選框
<input type="checkbox" id="Countries" value="Ind">India</input>
我的元素如何獲得輸出爲「印度」? 下面只返回工業
document.getElementById("Countries").value;
的HTML輸入標記得到相關的文本我有一個像下面如何在類型複選框
<input type="checkbox" id="Countries" value="Ind">India</input>
我的元素如何獲得輸出爲「印度」? 下面只返回工業
document.getElementById("Countries").value;
這是不可能的,因爲你的html
是錯誤的。
input
是一個自閉標籤,所以它應該是這樣的。
<input type="checkbox" id="Countries" value="Ind" />
所以沒有其他價值,你可以用JavaScript提取然後value
。 或者您應該使用data-attribute
與印度作爲價值。
HTML
<input type="checkbox" data-country="India" id="Countries" value="Ind" />
JS
var checkbox = document.querySelector('#Countries'); // or document.getElementById("Countries");
alert(checkbox.dataset.country);
這是可能的,因爲你可以在我的文章中看到 – 2014-09-28 08:13:23
@StevenWeb是的,你是對的,但是你的html無效。或者它是XHTML。 – TeeDeJee 2014-09-28 08:15:25
這個HTML是不正確的,我提到它! – 2014-09-28 08:16:45
我不認爲你可以,因爲這是不合法的HTML代碼。
輸入標籤爲空,意味着它只能包含屬性。因此,沒有</input>
來關閉它。
雖然有辦法存儲數據。
從HTML 5開始,就有可以放在任何元素上的數據屬性。你可以做這樣的事情:
<input type="checkbox" id="Countries" value="Ind" data-something="India" />
// Inside JS
document.querySelector("#Countries").dataset.something
另一種替代方法是將p或跨度包圍在文本後面。
<input type="checkbox" id="Countries" value="Ind" />
<p id="CountriesText">You can get this value easily enough</p>
有一種方法可以在您不關心語義正確性時獲取值。
alert(document.getElementById('Countries').nextSibling.nodeValue);
<input type="checkbox" id="Countries" value="Ind">India</input>
出於完整性:
<label for="Countrie">India</label>
<input type="checkbox" id="Countrie" />
或
<input type="checkbox" id="Countrie" />
<label for="Countrie">India</label>
提到您shoult做一個輸入型這樣的0
或
<label>
<input type="checkbox" name="Countrie" />
India
</label>
在THIS POST 也提到了,然後用JavaScript來獲取coresponding label
值。
'input'是一個自閉標籤。 – melancia 2014-09-28 07:56:10
_Tag省略:必須有開始標記並且不得有結束標記._ [input](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input) – melancia 2014-09-28 07:57:32
不要忘記標記正確的答案,如果有一個給你1 – 2014-10-07 07:54:45