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?
我想大声告诉你2017-05-19 10:20:04
Replace picture 2 with this:
// test() 要指定this 为被点击的元素
test.call(this); // 利用call方法
MDN - Function.prototype.call
習慣沉默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