javascript - 添加在。 ('click' ) 函数用于新创建的按钮,单击之前触发事件

标签 javascript jquery html

首先,我一直在查看以前的答案并更改我的代码,但是我以前读过的解决方案都不适合我。基本上,我将所有问题和答案保存在 jStorage 中,我正在尝试创建一个评论页面,其中发布问题和答案,以及一个新按钮,将用户链接回回答问题的页面.

我使用两个函数,createReviewPage(),它为用户创建页面,显示问题和答案。我还有 reviewPageButton(int)。

基本上,我需要将 reviewPageButton() 函数附加到新创建的按钮,并且我一直在尝试使用 on.('click') 在创建函数时找到该函数的按钮,但是该事件在我之前触发甚至单击一个按钮。

我的第一个函数(注意我之前的一些尝试已被注释掉):

function createReviewPage() {
    var questions = [];
    for (var index = 1; index < 5; index++) {
        questions.push($.jStorage.get("question" + index));
    }
    for (var index = 0; index < questions.length; index++) {
        console.log(questions[index].questionText);
        $('#resultDisplay').append("<h2> You answered " + questions[index].chosenAnswer + " to the question " + questions[index].questionText + "</h2>");
        $('#resultDisplay').append("<input type = 'button' id = 'qbutton" + (index + 1) + "'/>");
        //     $('.qbutton' + (index + 1)).on("click", '#qbutton' + (index+1), invokeButton(index));
        //      $('body').on('click', '.qbutton'+(index+1),reviewPageButton(index));
        $('.qbutton'+(index+1)).on('click',reviewPageButton(index));
        $('#resultDisplay').append("<br> <br> <br>");
    }
}

还有我的 reviewPageButton()

function reviewPageButton(number) {
    var currentquestion = $.jStorage.get("question" + (number + 1));
    currentquestion.reviewed = "Yes";
    $.jStorage.set("question" + (number + 1), currentquestion);
    window.open("../src/questionpage" + (number + 1) + ".php", "_self");

}

最佳答案

reviewPageButton(index) 代表函数执行,尝试使用 reviewPageButton.bind(null, index) 代替。

关于javascript - 添加在。 ('click' ) 函数用于新创建的按钮,单击之前触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35365079/

相关文章:

jquery - 不透明度动画在 jQuery 和 CSS 中不起作用

javascript - 如何阻止超链接执行滑动切换事件

html - 菜单行为不当

javascript - 测试自定义 Angular Directive(指令)是否显示/隐藏元素

php - ReCaptcha 不接受任何字符串

javascript - 中间件不会捕获带有等待的 Promise 拒绝

javascript - 使用ajax在HTML表中显示嵌套的json

javascript - 语法错误 : Unexpected token, 应为 ", "

javascript - 多文件输入html不工作

javascript - 将 jQuery 与 Webpack 结合使用