【问题标题】:jQuery - Accessing object properties from within another object that was passed to an eventjQuery - 从传递给事件的另一个对象中访问对象属性
【发布时间】:2011-01-22 06:47:25
【问题描述】:

In an earlier question 我想出了如何将object 存储为properties。 现在,当object 通过事件但无法使其工作时,我正在尝试访问那些properties

<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>

【问题讨论】:

    标签: jquery object properties events


    【解决方案1】:

    这对你有用,将它附加到元素上,而不是作为对似乎略有变化的元素的引用(这是一个不同的.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);
      };
    });
    

    【讨论】:

      【解决方案2】:
      //clearly TestObject is no longer attached to the div, why?
      

      因为this 在这一行alert(jQuery.data($(this), "obj").testProperty); 返回您的函数上下文,所以您应该改用alert(jQuery.data($("#test"), "obj").testProperty);

      【讨论】:

      • 这也行不通,在jQuery.data() 中,您存储的是对DOM 元素的引用,这仍然不一样...在正常情况下,您不应该使用@ 987654326@,但改为.data()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-01
      • 2013-05-02
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多