开发者

Rails 3 + Jquery click nothing happen on first click

开发者 https://www.devze.com 2023-03-29 07:02 出处:网络
i have a problem with my jquery but unable to find why. When i click for the first time on my link, nothing happen. On the second click, my link work. here is my code.

i have a problem with my jquery but unable to find why. When i click for the first time on my link, nothing happen. On the second click, my link work. here is my code.

aplication_helper.rb
def link_to_share(name, url)
  link_to_function(name, "share_link(name, url)")
end

my jquery file

function share_link(link, url)
{
  $(link).click(function() {

    window.open('http://www.facebook.com/sharer.php?u='+ url, 'popupwindow', 'height=430,width=500')
  });
}

my view

<%= link_to_share 'Share', request.url %>

If i change my jquery function like

function share_link(link, url)
{
  $(link).live('click', function() {

    window.open('http://www.facebook.com/sharer.php?u='+ url, 'popupwindow', 'height=430,width=500')
  });
}

the script stop working.

in m开发者_运维技巧y Firebug debugger, i have no error on the first click, and in the second try with the live function, no error too.

I use jquery-uij from gemfile.

thanks.


To make your code work, remove the click handler

$(link).live('click', function() {
}

And just leave

function share_link(link, url)
{
    window.open('http://www.facebook.com/sharer.php?u='+ url, 'popupwindow', 'height=430,width=500')
}

You don't need to define the click handler, because you're using the link_to_function helper. The link_to_function helper, just calls the function you entered when you click that link.

For more information, check out the documentation. I didn't know about this helper, thanks for asking this question.


Is nothing at all happening or is the event handler being invoked but the window is not being opened? It could be an officious pop-up blocker. Put an alert() in the function to find out.


function share_link(link, url)
{
  $(link).click(function() {

    window.open('http://www.facebook.com/sharer.php?u='+ url, 'popupwindow', 'height=430,width=500')
  });
}

the problem with that code is that it adds the listener after the click event has occurred. So the reason nothing happens the first time is that there is no event handler yet. But on the 2nd click you are calling the event handler created with the first click. See if you can rework your code to maybe take share_link as the event handler function itself.

function share_link(event)
{
 ...
}
$(link).click(share_link);
0

精彩评论

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