为什么我无法使用 jquery 和 javascript 获取标签的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19228839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:28:59  来源:igfitidea点击:

why I can't get value of label with jquery and javascript?

javascriptjquerygetlabel

提问by r.r

I have a usual label

我有一个普通的标签

<label class="mytxt"  style="color: #662819;" id ="telefon"></label>

I am settinga value like this:

我正在设置这样的值:

document.getElementById('telefon').innerHTML = userDetails.phone;

after a label has some value like "123".

在标签具有某些值后,例如"123".

In a pagesource, I have a label without setted value inside "><" but I see as output it alright:

pagesource 中,我在 "><" 中有一个没有设置值的标签,但我认为输出正常:

pagesource: <label class="mytxt"  style="color: #662819;" id ="telefon"></label>

My problem is when I like to GETa value. I tried standardslike:

我的问题是当我喜欢GET一个值时。我尝试了以下标准

value = $("#telefon").val(); 
document.getElementById('telefon').value 

nothing works, value is always "not defined". Why is this so, even if I see it in the browser?

没有任何作用,价值总是“未定义”。为什么会这样,即使我在浏览器中看到它?

回答by Adil

You need text()or html()for label not val()The function should not be called for label instead it is used to get values of input like text or checkbox etc.

You need text()or html()for label notval()不应为 label 调用该函数,而是用于获取输入值,如文本或复选框等。

Change

改变

value = $("#telefon").val(); 

To

value = $("#telefon").text(); 

回答by Dan Heberden

Label's aren't form elements. They don't have a value. They have innerHTMLand textContent.

标签不是表单元素。他们没有value. 他们有innerHTMLtextContent

Thus,

因此,

$('#telefon').html() 
// or
$('#telefon').text()

or

或者

var telefon = document.getElementById('telefon');
telefon.innerHTML;

If you arestarting with your form element, check out the labelslist of it. That is,

如果你正在开始你的表单元素,检查了labels它的名单。那是,

var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea