【问题标题】:How to add id in jquery?如何在jquery中添加id?
【发布时间】:2016-11-18 04:46:57
【问题描述】:

我在 jquery 中创建了一个对话框。并且有一个名为“保存”的按钮。我需要在这个保存按钮上添加一个 id。我怎样才能在 jquery 中实现这一点。这是我的代码

$(function() {
    $( "#dialog" ).dialog({

         height: 400,
      width: 650,
      modal: true,
      buttons: {

        Save: function() {
          dialog.dialog( "close" );
        }
      },
      close: function() {
        form[ 0 ].reset();
        allFields.removeClass( "ui-state-error" );
      }

    });
});

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

使用$("button").attr("id","testid");

【讨论】:

    【解决方案2】:

    试试这个:

    $(element).attr('id', 'YourNewID');
    

    【讨论】:

      【解决方案3】:

      Save函数有一个参数event,它的目标是按钮的DOM元素,然后你可以在函数内部设置id,如下所示:

      Save: function(event) {
         $(event.target).attr('id', 'your-id');
      }
      

      关于buttons 属性的specification 说:

      指定应在对话框上显示哪些按钮。回调的上下文是对话框元素;如果您需要访问按钮,它可用作事件对象的目标。

      【讨论】:

        【解决方案4】:
        $(function() {
            $( "#dialog" ).dialog({
              height: 400,
              width: 650,
              modal: true,
              buttons: {
                save: {
                  text: "Save",
                  id: "my-button-id",
                  click: function(){
                    dialog.dialog( "close" );
                  }   
                }
              }
              ...
            });
        });
        

        【讨论】:

        • 非常感谢您的有效回复。我还有一个疑问,如何在我的 js 文件中访问此 ID。$("#rm-button-id").click(function(){ alert("here"); });
        • 这是我现在使用的。
        【解决方案5】:

        这是最简单的

        $(selector).attr('id', 'TheID');
        

        【讨论】:

          猜你喜欢
          • 2010-12-12
          • 1970-01-01
          • 1970-01-01
          • 2013-01-09
          • 1970-01-01
          • 1970-01-01
          • 2012-01-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多