用val()获得一个空值 [英] Getting an empty value with val()
问题描述
我有一张表,其中一行是
< td class =firstRow>
firstRow
在我的java脚本类中,我调用了两个函数
,第一个随机赋值给了这个id,所以当我加载我的时候页面我每次都会得到一个不同的单词:这部分工作是
$(#randomWordToTranslate)。html(current_dict [listOfKeys [Math.floor(Math.random()* listOfKeys。当按钮被点击时,按钮侦听器中的第二个尝试获取该字段内的单词的值的第二个内容
var spanishWord = $(#randomWordToTranslate);
var inputValue = $(spanishWord).val();
但是当我做console.log(inputValue)时,我在日志中打印一个空行。
任何想法?
谢谢
由于< span>
不是< input>
标记(或其他形式输入,如< select>
),它不会有 .val()
(value)。相反,您需要 .html()
或 .text()
:
var spanishWord = $(#randomWordToTranslate);
var inputValue = spanishWord.text();
//或者:
var inputValue = spanishWord.html();
I have table with the following id inside one of the rows
<td class="firstRow"> <span id="randomWordToTranslate"></span></td>
the firstRow
class just include padding preferences in css.
In my java script class, I am calling two functions
the first randomly assigned a value to this id , so when I am loading my page I will get a different word each time : this part is working
$("#randomWordToTranslate").html(current_dict[listOfKeys[Math.floor(Math.random() * listOfKeys.length)]]);
the second inside a button listener trying to get the value of the word inside this field whenever the button is clicked
var spanishWord = $("#randomWordToTranslate");
var inputValue = $(spanishWord).val();
but when I doing console.log(inputValue) I am printing an empty row into my log. Any ideas?
thanks
Since the <span>
isn't an <input>
tag (or other form input like <select>
), it will not have a .val()
(value). Instead, you need either .html()
or .text()
:
var spanishWord = $("#randomWordToTranslate");
var inputValue = spanishWord.text();
// Or:
var inputValue = spanishWord.html();
这篇关于用val()获得一个空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!