jQuery-从传递给事件的另一个对象中访问对象属性

前端之家收集整理的这篇文章主要介绍了jQuery-从传递给事件的另一个对象中访问对象属性 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

In an earlier question我想出了如何将对象存储为属性.
现在,当对象通过事件传递但无法正常工作时,我尝试访问这些属性

<script language="javascript">
$(document).ready(function() {
    //create a TestObject
    function TestObject() {
      this.testProperty = "green";
    }

    //and an instance of it
    var testObject = new TestObject();

    //attach this instance to the div as a property
    var test;
    test = $('#test');//the div
    jQuery.data(test,"obj",testObject);

    //prove it worked and the TestObject is assigned
    alert(jQuery.data(test,"obj").testProperty);//works

    $('#test').click(TestClick);
    //test.click(TestClick); doesn't work either

    function TestClick() {
        alert($(this).attr("id"));//displays "test" - works
        alert(jQuery.data($(this),"obj").testProperty);
        //testProperty is null or not an object??
        //clearly TestObject is no longer attached to the div,why?
        //Or have I attached it the wrong way?    
        //alert(jQuery.data(this,"obj").testProperty); doesn't work either
    };
});
</script>
<body>
    <form id="form1" runat="server">
        <div id="test">Here is a test div</div>
    </form>
</body>
最佳答案
这将为您工作,将其附加到元素上,而不是作为对似乎略有变化的元素的引用(这是一个不同的.data()调用,see here for info):

$(document).ready(function() {
  function TestObject() {
    this.testProperty = "green";
  }

  var testObject = new TestObject();
  var test = $('#test').data("obj",testObject);

  alert(test.data("obj").testProperty);

  $('#test').click(TestClick);
  function TestClick() {
    alert($(this).attr("id"));
    alert($(this).data("obj").testProperty);
  };
});

猜你在找的jQuery相关文章