Jquery Else声明不起作用

时间:2013-01-25 14:30:29

标签: jquery html if-statement

我的问题是这里的 else 部分似乎不起作用。 我已经在网上寻找解决方案,尽管有很多问题与我的问题完全一样,但答案似乎总是不同。

这是我点击的按钮

<input type="submit" value="4">

我也有一个这样的按钮:

<input type="submit" id="b1" value="Back">

我的目标是找出是否点击了带有ID的按钮。


var specify = "";
var prevpos = 0;

$('input[type=submit]').click(function(){
    specify = $(this).attr('value');

    if($(this).attr('id').substring(0,1) == "b")
    {
       $("html, body").animate({scrollTop: prevpos}, 777);
       $(".right").animate({opacity: 0.0}, 200);
       $(".left").animate({opacity: 1.0}, 200);
       // more stuff here                           
    }   
    else
    {
       $("html, body").animate({scrollTop: prevpos}, 777);  
       // more stuff here
    }
});

一如既往,非常感谢任何帮助!

3 个答案:

答案 0 :(得分:4)

您的代码存在的问题是因为当您单击没有id的按钮时,您在null上调用substr(),这将导致错误。

请改为尝试:

var specify = "";

$('button').click(function () {
    specify = $(this).attr('value');
    var id = $(this).attr('id');

    // check there is an id, and if so see if it begins with 'b'
    if (id && id.substring(0, 1) == "b") {
        alert("You clicked the button WITH an id");
    } 
    else {
        alert("You clicked the button WITHOUT an id");
    }
});

Example fiddle

答案 1 :(得分:2)

var specify = "";
var prevpos = 0;

$('input[type=submit]').click(function(){
    specify = $(this).attr('value');

    if($(this).attr('id') && $(this).attr('id').substring(0,1) == "b")
    {
       $("html, body").animate({scrollTop: prevpos}, 777);
       $(".right").animate({opacity: 0.0}, 200);
       $(".left").animate({opacity: 1.0}, 200);
       // more stuff here                           
    }   
    else
    {
       $("html, body").animate({scrollTop: prevpos}, 777);  
       // more stuff here
    }
});

在检查元素值之前,您可能需要检查元素是否具有id属性。

答案 2 :(得分:0)

前段时间我有类似的要求,这是我的解决方案:

var specify = "";
var prevpos = 0;

$('input[type=submit]').click(function(e){ //Note the addition of 'e'
    var id = e.target.id; // If the element has no ID you should get an empty string here

    specify = $(this).attr('value');

    if( id.match(/^b/) ) { // This is a regular expression, if the ID starts with 'b' then it matches
       $("html, body").animate({scrollTop: prevpos}, 777);
       $(".right").animate({opacity: 0.0}, 200);
       $(".left").animate({opacity: 1.0}, 200);
       // more stuff here                           

    } else {
       $("html, body").animate({scrollTop: prevpos}, 777);  
       // more stuff here
    }
});