jQuery .click函数不起作用

jQuery .click function is not working?

本文关键字:不起作用 函数 click jQuery      更新时间:2023-09-26

我有一个javaScript文件,其中我试图通过使用jQuery绑定一个名为change的函数,我尝试了这个代码,但它不工作?

 script.js
 for(var i=1; i<suggestionList.length; i++)
            {
                $list.append("<li>" + suggestionList[i] + "</li>");
                // attach handler for click on the suggestions
                $list.find("li").eq(i).click(function() {
                    change(suggestionList[0], suggestionList[i]);
                });
            }

    function change(changeto,changewith)
        {
            var replaceto=document.getElementById(changeto).innerHTML;
            var replacewith=changewith;
            var text1=document.getElementById("para").innerHTML;
            var afterRe=text1.replace(replaceto,replacewith);
            document.getElementById("para").innerHTML=afterRe;
        }

请帮助我为什么我的代码不工作?

您不能在click事件的for循环中使用i。我在这里设置了一个演示文件。检查是否有帮助

for(var i=1; i<suggestionList.length; i++)
{
    $list.append("<li>" + suggestionList[i] + "</li>");
     // attach handler for click on the suggestions
}
$list.find("li").click(function() {
    changewith=$(this).html();
    change(suggestionList[0], changewith);
});