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

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

Passing a variable into an alert

jquery

提问by conbask

When the correct string, foo, is entered into .guessI am trying to pull the value from .clicksand 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 clicksvariable 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

.val()is primarily used for getting the value of form input elements.

.val()主要用于获取表单输入元素的值。

I think you want to use $(".clicks").text(), OR $(".clicks").html(),which will return "0".

我想你想使用$(".clicks").text(), OR $(".clicks").html(),它会返回"0"

回答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();
    }
});?