开发者

jQuery Event for link click not firing

开发者 https://www.devze.com 2022-12-19 10:23 出处:网络
I have the following function: $(\"a#mylink\").click(function(e){ e.preventDefault(); $.ajax({ url: $(this).attr(\"href\") });

I have the following function:

  $("a#mylink").click(function(e){
            e.preventDefault(); 
            $.ajax({ url: $(this).attr("href") }); 
            $(this).parent().parent().fadeOut("slow");
          });

A link is being created on the page with the following code:

'<div  style="margin-top: 4px; border: solid 2px #515151; color: 开发者_JAVA技巧#515151; width: 300px;"><span style="padding-left: 4px">' +
                file.name+
                '    </span><div style="float: right; padding-right: 4px;"><a class="mylink" href="remove.aspx?img='+safeUrl+'">Remove</a></div>' +
                '</div>'

When I click the link, a new page pops up and it does not hit my function. Any ideas?


a.mylink not a#mylink

# is the ID selector, and you have mylink set as a class.


You're putting "mylink" in the "class" but your selector is looking for an "id" value. Try:

$('a.mylink').click( ... )

or else use "mylink" as the "id" value for the anchor tag.


This link is being added dynamically? Sounds like you need to use live()

// incidentally, drop the "a" from "a.mylink" it's unnecessary and slows it down
$(".mylink").live('click', function () { ... });

As the others saw (and I didn't) #xyz matches an id, whereas .xyz matches a class. You have a class on your link, so you need to use a dot.


Turns out that since I was adding my link durning run-time, I needed to re-bind my click event.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号