【问题标题】:Why are elements null in jquery, yet exist with document.getelementbyid()为什么 jquery 中的元素为空,但与 document.getelementbyid() 一起存在
【发布时间】:2010-11-18 17:38:59
【问题描述】:

我正在尝试使用 document.ready 将一些 jquery 附加到网格视图中的复选框:

  $(document).ready(function()
  { 
       var chkBox= document.getElementById("gvTimeSheet_ctl01_chkAll1");
       //I can alert chkBox.id, element exists

       var name = $("input[name='gvTimeSheet$ctl01$chkAll1']");
       //Here, when I alert the id, I get a null

       var ID = $("#gvTimeSheet_ctl01_chkAll1");
      //Here, when I alert the id, I get a null

       var withClass = $(".chkAll1Class");
       //Here, when I alert the id, I get a null

       var withClass2 = $(".Bill1");
       //Here, when I alert the id, I get a null

       //This line causes the browswer to crash and gives me the following error
       //Microsoft JScript runtime error: 'null' is null or not an object
       $("#gvTimeSheet_ctl01_chkAll1").click(function()           
       {
           var checked_status = this.checked;
           $("input[class=Bill1]").each(function()
           {
           this.checked = checked_status;
           });

       });

    });*/

那么,为什么尝试在 jquery 中查找 null 对象,却存在于同一方法中的常规 javascript 中?我在这里想念什么。我在此方法正上方的脚本标记中引入了 jquery js 文件。我似乎无法使用 jquery 在此页面上找到任何对象。在其他页面上,我可以。

【问题讨论】:

  • 你在使用其他的 Javascript 库吗?
  • 你能贴出生成的 HTML 源代码吗?也许在jsbin.com 发布一个沙盒会有助于理解。

标签: asp.net jquery gridview checkbox


【解决方案1】:
var val = $("input:radio[name$='rdoselect']:checked").val();           
if (val == 1) {            
    $('[id$=divDate]').attr('disabled', true);                 
}else {             
    $('[id$=divDate]').attr('disabled', false);
}

【讨论】:

  • 问题以“为什么”开头。代码非常适合解释如何,但这似乎无法解释原因。
【解决方案2】:

您添加此代码的页面是否已经包含 Prototype JavaScript 库?

jQuery 的 "$" 方法永远不会返回 null,所以这应该不是问题:

// This line causes the browswer to crash and gives me the following error
// Microsoft JScript runtime error: 'null' is null or not an object
$("#gvTimeSheet_ctl01_chkAll1").click(function() { .... });

所有关于需要使用.attr('id') 的cmets 仍然存在(尽管我自己更喜欢$('#whatever')[0].id。)

【讨论】:

    【解决方案3】:
     var ID = $("#gvTimeSheet_ctl01_chkAll1");
    

    这将返回一个 jQuery 对象,而不是一个 ID。 ID.id 也将是未定义的。要获取 ID,您需要:

    var ID = $("#gvTimeSheet_ctl01_chkAll1").attr("id");
    

    【讨论】:

      【解决方案4】:

      从 jQuery 选择器生成的对象实际上是 DOM 对象的包装器,因此您不能像访问 DOM 对象一样访问它。

      如果您只是提醒“name.id”,从上面的第一个示例中,jQuery 包装器上不会有任何此类属性。尝试按如下方式提醒您的 ID:

      alert(name.attr("id"));
      

      【讨论】:

        猜你喜欢
        • 2012-02-24
        • 1970-01-01
        • 2017-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-12
        • 2012-10-04
        相关资源
        最近更新 更多