weixin_33737134 2015-02-03 03:42 采纳率: 0%
浏览 160

如何获取按钮ID

I have a file Index.aspx connected to file seatbooks.js.
In Index.aspx has a button with id Indexbutton. Indexbutton has eventonclick='book_ticket()'. book_ticket() method is include on seatbooks.js. How to get button id (Indexbutton) on book_ticket(). Please check my code bellow:

 <input type="button" name="submit" class="ui-state-default ui-corner-all" id="indexbutton" onclick="book_tickets()" value="Book Seat" />

Above is my code on Index.aspx. And this is my book_ticket() code:

function book_tickets() {    
var tickets = jQuery('.seat.selected').length;
//seatId = $('#button').attr('id');   
//var btnId = this.attr('id');
//console.log(seatId);
if(tickets==0)
{
    alert('Please select at least one seat to continue...!');
    return false;
} else if (tickets > 1)
{
    alert('Please select only one seat to continue...!!');
    return false;
}else
{
    x = jQuery('.seat.selected').toArray();
    jQuery('#seat-form-data').html('');
    jQuery('.seat.selected').each
    (
        function () {
            var ydata = jQuery(this).html();
            xdata = ydata.replace("[class]", "");
            jQuery('#seat-form-data').append(xdata);
        }
    );
    jQuery('#seat-form-data').append('<input type="submit" value="submit">');
    jQuery('#seat-form-data input[type="submit"]:first').trigger('click');
    //console.log(xdata);


    // Link to open the dialog
   $("#dialog").dialog("open");
    //event.preventDefault();
}

}

I had tried:

seatId = $('#button').attr('id');   
var btnId = this.attr('id');

And tried to show it on console. But it doesn't work. It say undefine. I want to get indexbutton (button id) on book_tickets().

  • 写回答

1条回答 默认 最新

  • weixin_33738578 2015-02-03 03:44
    关注

    Since you have a hard coded ID why do you want to access it via any other way. You can hard code the button Id isn't it?

    Anyway, one solution is to pass the dom reference to the function like

    <input type="button" name="submit" class="ui-state-default ui-corner-all" id="indexbutton" onclick="book_tickets(this)" value="Book Seat" />
    

    then

    function book_tickets(el) { 
        var buttonId = el.id;
        ....
    }
    

    Your code

    seatId = $('#button').attr('id');
    var btnId = this.attr('id');
    

    $('#button').attr('id') will look for an element with id button and if it is found it will return the id of that element which is again button, same way this inside the book_tickets method does not refer to the button, it is the window object so this.attr('id') will fail.

    评论

报告相同问题?

悬赏问题

  • ¥15 Qt安装后运行不了,这是我电脑的问题吗
  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上
  • ¥50 有没有适合匹配类似图中的运动规律的图像处理算法