Function not calling within an onclick event

后端 未结 6 1503
情歌与酒
情歌与酒 2020-12-08 14:29

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 val         


        
6条回答
  •  自闭症患者
    2020-12-08 14:39

    There's a much neater and more jQuery way to assign the click action.

    function init() {
        $('a').each(function() {
            if(valid_url.test($(this).attr('href'))){
                $(this).click( function() { open_litebox('hi'); });
            }
        });
    }
    

    This solves the scope problem as described in the other answers. If you need to call open_litebox() with parameters, wrap it inside an anonymous function like I did, or else the function will be called and then the return value is passed to the click action. Otherwise, with no parameters to pass, the assignment is simpler:

    $(this).click( open_litebox );
    

提交回复
热议问题