函数不在onclick事件中调用 [英] Function not calling within an onclick event

查看:89
本文介绍了函数不在onclick事件中调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在每个youtube链接的末尾添加一些HTML以在litebox中打开播放器。这是我的代码到目前为止:
$ b $

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);
  }
});

它可以在youtube链接之后注入一些HTML,如下所示:

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')">

但是当我点击这个 open_litebox()函数不会被调用。看看错误控制台,我可以看到一个错误,指出 open_litebox没有被定义,但我已经定义了它。

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?

谢谢。

推荐答案

当你第一次开始使用jQuery时,这是一个常见的问题。这里的问题是,你已经定义了jQuery范围内的函数,这意味着它不能像调用普通函数那样调用它。解决您的问题的方法是将您的函数定义移动到您编写的匿名就绪函数之外,如下所示:

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.

这篇关于函数不在onclick事件中调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆