jQuery 将变量传递给警报
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10886707/
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
Passing a variable into an alert
提问by conbask
When the correct string, foo
, is entered into .guess
I am trying to pull the value from .clicks
and pass it into an alert. When I load the page with my current code (below) the alert reads Correct! You guessed it in clicks.
. Why is the clicks
variable not being passed?
当输入正确的字符串 , 时foo
,.guess
我试图从中提取值.clicks
并将其传递到警报中。当我使用当前代码(如下)加载页面时,警报显示为Correct! You guessed it in clicks.
. 为什么clicks
不传递变量?
Thanks
谢谢
jQuery:
jQuery:
$('.guess').keyup(function() {
if ($('.guess').val() == "foo") {
var clicks = $('.clicks').val();
alert('Correct! You guessed it in ' + clicks + ' clicks.');
location.reload();
}
});
HTML:
HTML:
<div class="bar">
<h2 class="clicks">0</h2>
<input type="text" class="guess" />
</div>
回答by matt b
回答by Zoltan Toth
$('.guess').keyup(function() {
if ($('.guess').val() == "foo") {
var clicks = $('.clicks').text(); // .text() instead of .val()
alert('Correct! You guessed it in ' + clicks + ' clicks.');
location.reload();
}
});
回答by thecodeparadox
$('.guess').keyup(function() {
if ($.trim( this.value ) == "foo") {
var clicks = $('.clicks').text();
alert('Correct! You guessed it in ' + clicks + ' clicks.');
location.reload();
}
});
回答by Tats_innit
Working democlick here :) http://jsfiddle.net/QSrWs/
工作演示点击这里:) http://jsfiddle.net/QSrWs/
please use api: .text()
请使用api: .text()
This will help you to understand the difference: Difference between val() and text()
这将帮助您了解区别:val() 和 text() 之间的区别
Val() works on input elements (or any element with a value attribute?) and text() will not work on input elements. Val() gets the value of the input element -- regardless of type. Text() gets the innerText (not HTML) of all the matched elements:
Val() 适用于输入元素(或任何具有 value 属性的元素?)而 text() 不适用于输入元素。Val() 获取输入元素的值——与类型无关。Text() 获取所有匹配元素的innerText(不是HTML):
Hope this helps,
希望这可以帮助,
code
代码
$('.guess').keyup(function() {
if ($('.guess').val() == "foo") {
var clicks = $('.clicks').text();//$('.clicks').val();
alert('Correct! You guessed it in ' + clicks + ' clicks.');
location.reload();
}
});?