0

我的问题是这里的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
    }
});

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

4

3 回答 3

4

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

试试这个:

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");
    }
});

示例小提琴

于 2013-01-25T14:36:03.613 回答
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 属性。

于 2013-01-25T14:35:59.690 回答
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
    }
});
于 2013-01-25T14:53:23.270 回答