如何在JavaScript中检查变量值

How to check variable value in JavaScript?

本文关键字:检查 变量值 JavaScript      更新时间:2023-09-26

使用下面的代码,单击按钮asc应该会隐藏按钮ascdesc,然后提醒值。单击desc按钮时,应为asc执行show(),为desc执行hide()。该值应再次显示在警报消息中。

我怎样才能得到这种行为?

<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<form method="post" id="form_content">
    <button id="desc" name="desc" value="desc" onclick="reply_click(this.id)">desc</button>
    <button id="asc" name="asc" value="asc" onclick="reply_click(this.id)" style="display:none;">asc</button>
</form>
<script>
function reply_click(clicked_id)
{
    var content = clicked_id;
    if (var content = asc) {
        $('#asc').hide();
        $('#desc').show();
    }
    if (var content = desc) {
        $('#asc').show();
        $('#desc').hide();
    }
    alert(content);
}
</script>
if (content === 'asc') {
    $('#asc').hide();
    $('#desc').show();
}
if (content === 'desc') {
    $('#asc').show();
    $('#desc').hide();
}

不确定你需要什么,但试试这个:http://jsfiddle.net/kg005f4v/

<form method="post" id="form_content" action="Javascript:void(0);">
    <button id="desc" name="desc" value="desc">desc</button>
    <button id="asc" name="asc"  value="asc">asc</button>
</form>
#desc{
    display:none
}
$(document).ready(function(){
    $('#form_content button').click(function(){
        $('#form_content button').toggle();
        alert(this.id);
    });
});

在javascript中比较字符串值的方法是使用===运算符。由于您要查找的元素的id是if语句中的字符串,请尝试以下操作:

if(content === 'asc') 

和:

if(content === 'desc')

这将id与字符串"asc"和字符串"desc"进行比较。

===运算符意味着相等的值和相等的类型,因此它检查左边的var是否与右边的var具有相同的类型(在这种情况下是字符串)和相同的值。