Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

javascript - Function not calling within an onclick event

I want to add some HTML to the end of every youtube link to open up the player in a litebox. This is my code so far:

$(document).ready(function() {
  var valid_url = new RegExp('youtube.com/.*v=([a-zA-Z0-9_-]+)');
  var image_data = 'base64 encoded image';

  init();

  function init() {
    $('a').each(function() {
      if (valid_url.test($(this).attr('href'))) {
        $(this).after( ' <img src="' + image_data + '" onclick="open_litebox('hi');" />' );
      }
    });
  }

  function open_litebox(param) {
    alert(param);
  }
});

It works to the point where it injects some HTML after the youtube link, like so:

<img src="base 64 data" onclick="open_litebox('hi')">

But when I click this the open_litebox() function doesn't get called. Looking in the error console I can see an error that says open_litebox is not defined, but I have defined it.

I'm pretty clueless as to what's going wrong here, could someone lend me a hand?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a common problem when you first start working with jQuery. The problem here is that you have defined the function within the jQuery scope, which means that it is not accessible by just calling it like a normal function. A solution to your problem is to move your function definition outside the anonymous ready function that you written, like so:

$(document).ready(function() {

    // do your stuff here

});

// define your functions here 
function my_func() {

}

Oh and I would suggest doing the same for your variables that you have defined. Move them outside your ready function as well, because you will have the same problems as you did with your functions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...