search

Home  >  Q&A  >  body text

javascript - Problems with calling functions in JQuery click events

Figure 2 calls the function in Figure 1, and the output is Undefined, but in Figure 2, the same code is used in the JQ click event and the output result is. Then I declared a variable obj in the test function to obtain all objects with the attribute name=component_checkbox[]. At this time, there is output when calling this function in the JQ click event. My question is why the test() in Figure 2 does not output the result but is undefined when the code in Figure 1 is used?

曾经蜡笔没有小新曾经蜡笔没有小新2736 days ago387

reply all(3)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-19 10:20:04

    Replace picture 2 with this:

    // test()  要指定this 为被点击的元素 
    test.call(this);  // 利用call方法 

    MDN - Function.prototype.call

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-19 10:20:04

    Because the scope of this is different, this in the click closure refers to the checkbox you selected, and in the test function, this refers to the window or other object

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-19 10:20:04

    In Figure 1, $(this) has no pointing value

    reply
    0
  • Cancelreply