我的按钮不起作用

时间:2014-02-26 11:57:56

标签: javascript html function button

我的JS中有一些html,除了按钮之外的所有东西都有效。出现输入按钮,但是当我单击它时,没有任何反应。

function updateFavourite(video) {
document.getElementById("favourite").onclick = function () { 
blacklist[video["id"]] = true;
myfavourite.push(video);

var html = 
    "<input onclick='remove(video);' value='Remove' type='button'></input>" +
    "<li class=\"saved\">" +
    "<img class= \"img-rounded\" src=\"{0}\"/>" +
    "<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchFavouriteVideo(\{1}\)\"><span></span>{2}</a></b><br>" +
    "by {3}<br>" +
    "{4} | {5} views</p>" +
    "</li>";

$("#myfavourite").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
setVideoF(video);
}
}

致电方法:

function remove (video) { 
alert('Favourites removed');
}

2 个答案:

答案 0 :(得分:0)

它失去了对video变量的访问权限,删除了onclick属性并使用jQuery绑定其事件,并使用JavaScript Closure来保证video变量的安全:

function updateFavourite(video) {
    var clickFunc = (function (video) {
        return function () {
            blacklist[video["id"]] = true;
            myfavourite.push(video);
            var html =
                "<input class='removeButton' value='Remove' type='button' />" +
                "<li class=\"saved\">" +
                "<img class= \"img-rounded\" src=\"{0}\"/>" +
                "<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchFavouriteVideo(\{1}\)\"><span></span>{2}</a></b><br>" +
                "by {3}<br>" +
                "{4} | {5} views</p>" +
                "</li>";
            $("#myfavourite").prepend(html.format(video["thumbnail"],
            video["id"],
            video["title"],
            video["uploader"],
            video["length"],
            video["views"]));
            $("#myfavourite .removeButton").click(function () {
                remove(video);
            });
        };
    })(video);
    document.getElementById("favourite").onclick = clickFunc;
}

答案 1 :(得分:0)

您的代码正在生成动态html,因此Click事件未正确注册。需要更新一点html。使用“removeVideo”类到您的按钮并使用jquery 注册动态元素的click事件。

    $('body').on('click','.removeVideo', function(){
        $(this).val("Clicked");
    });

Insted of $('body')你可以使用最近的(但不是动态元素)父级。

相关问题