为什么on函数在动态创建的div上不起作用?

时间:2019-05-21 11:01:19

标签: jquery

'twoFunctions'函数在单击按钮时起作用,但在动态创建的div'.alternatives'中单击时不起作用;但是,它在第​​一次单击时起作用一次,而在下次单击时不起作用。我有两个问题: (i)如何使以下代码起作用:

$('.alternatives').on('click', function() {
    twoFunctions();
});

(ii)div的ID在单击时不断变化。如何将ID分配给div      以便它们保持固定状态。

选项

var antonyms = [

    {
        question: "soft",
        options: ["dark", "white", "heavy", "hard", "down", "pretty"],
        answer: "hard",

    },

    {
        question: "beautiful",
        options: ["pretty", "ugly", "happy", "wonderful", "up","high"],
        answer: "ugly",


    },

    {
        question: "happy",
        options: ["red", "green", "blue", "low", "go", "yellow"],
        answer: "sad",

    } ]


// Showing options one at a time 

x = "";

var i = 0;

function showOpt() {

    document.getElementById('holder').innerHTML = x;

    for (j = 0; j < antonyms[i].options.length; j++) {

    if (i < antonyms.length) {

    $('#holder').append("<div id=" + antonyms[i].options[j] + " 
    class='alternatives'>" + antonyms[i].options[j] + "</div>");

        }

    }

    i++;
}

showOpt();


// Showing question one at a time

k = 0;

function showQuest() {

    if (k < antonyms.length) {

    $('#holder').append("<div id='quest'>" + antonyms[k].question + " 
    </div>");

        k++;
    }
}

showQuest();


// Calling two functions     

function twoFunctions() {

    showOpt();

    showQuest();

}

0 个答案:

没有答案