Recently, I used Jquery when working on a project. Novices are learning jquery. I encountered some "strange" problems (masters, please don't blame me).
Thanks to Mr. ClassYuan for his support. ClassYuan’s blog. http://www.classyuan.com/. Here are some:
1. When loading an event with an HTML element, the event will be executed at the same time as loading.
Error code:
view source
PRint?1 $("#btnLoad").bind("click",GetProduct());
correct code
view source
print?1 $("#btnLoad").bind("click", function() { GetProduct() });
In this code, I ignored the Bind method. The API explanation is bind(type,[data],fn)
I mistakenly regarded fn as a simple function. As a result, this code will execute the fn once when loading.
This is an oversight in writing format. I hope someone who knows the reason can give me some advice.
2. The problem of variable scope. (It seems that this is not a problem of jquery. It is the difference between js and .net..)
view source
print?1 function text() {
2 for (var i = 0; i < 3; i++) {
3 $("<a>Delete</a>").attr({ id: "hr_" + i, href: "javascript:;" }).addClass("btnCSS").bind("click", function () { tes(i) }).appendTo(".div_list");
4}
5}
6 function tes(id) {
7 alert(id);
8}
This function. I want it to alert the corresponding id. The result is that the answer is very agreeable. It is a function with 3 <a> tags. When it pops up, it is always 3..
After looking at it...I understand
Regarding the problem of variable scope, the parameter passed to the tes function is the value of i after the loop ends, so all are 3.
This seems to be different from .net.
Finally, the solution - -.. Just pass $(this) in
3. Issues with the order of event execution
view source
print?1 <a target="_blank" title="Iphone" >
2 <img id="proImg7_2" src="" alt="Iphone" style="width:70px; height:60px; border:none;" />
3 </a>
The onclick event is bound to this image. The content of the event is to add an href attribute to the parent of the <img> tag.
But after the event is executed, it will jump directly to the link of the a tag. After analysis.
It should be that the click is executed before the href, that is, when the image is clicked, the A tag already has the href, and then the A tag is triggered at the same time.
Solution.. Remove the outer a tag of <img>.. Then modify the event
view source
print?1 idwrap(' <a href=" http://www.QQ.com"></a>' );
The above are the problems that I, a novice, encountered when using jquery for the first time. I will leave them here and treat them as a process of growth. Dear veterans, don’t complain..