简体   繁体   English

Javascript`onclick`在单独的JS文件中不起作用

[英]Javascript `onclick` doesn't work in separate JS file

I have to delete some answer so I used onclick event. 我必须删除一些答案,所以我使用了onclick事件。 This event only worked in same html page within the script tag, but it doesn't working on separate js file. 此事件仅在script标记内的同一html页面中有效,但不适用于单独的js文件。

editquestion.php editquestion.php

<a href="javascript:void(0);" title="delete" onClick="deleteAnswer('<?php  if($option->answerId != ''){ echo "{$option->answerId}"; } ?>','old');"><i class="icon md-recycle"></i></a>

user.js user.js

function deleteAnswer(uid,value){
  //alert(uid);
  if(value=='old'){
    $("#answer_form_group_"+uid).empty().hide();
    $("#answer_form_group_"+uid).append("<input type='hidden' name='deleteAnswer[]' value='"+uid+"'>");
    } else {
    $("#answer_form_group_"+uid).remove();
  }
}

function addans(){
$('.addans').unbind("click");
$('.addans').on("click",function(e){
    if ((($('#ansform').find(".form-group").length > 4)&&($("#sel1").val() == "multiplechoice"))||
        (($('#ansform').find(".form-group").length > 1)&&($("#sel1").val() == "trueorfalse"))||
        (($('#ansform').find(".form-group").length > 4)&&($("#sel1").val() == "multipleselect"))){
            noty({ text: 'your exceeded the maximium limit',type: 'error',modal:true,timeout:1000});
    } else {
        if(($('#ansform').find(".form-group").length > 0) &&($("#sel1").val() == "")){
            noty({ text: 'select Type of Question ',type: 'warning',modal:true,timeout:1000});
            } else {
            var uid = generateUid();
            var input_type = ($("#sel1").val() == "multiselect")?"checkbox":"radio";
            $('#ansform').append(     
            '<div class="form-group" id="answer_form_group_'+uid+'">'+
            '<div class="input-group">'+
            '<input type="text" id= "ans_'+uid+'" class="ans form-control input-lg ans inline" placeholder="Write answers here" name="ans[]">'+'&nbsp;&nbsp;'+
            '<input type="hidden" name="crt[]" value="0" />'+
            '<input type="'+input_type+'" id= "ctr_'+uid+'" class="correct" name="crt[]" value="1">'+'&nbsp;&nbsp;'+
            '<a href="javascript:void(0);" title="delete" onClick="deleteAnswer(\''+uid+'\',\'new\')"><i class="icon md-recycle"></i></a>'+
            '</div>'+
            '</div>'
            ); 
        }   
        e.preventDefault();
    }
});
}

function deleteAnswerOption(){
$("#ansform").off('click','.answer-delete');
$('#ansform').on('click', '.answer-delete', function(e) {
    e.preventDefault();
    //alert($(this).parent().parent().parent().attr('class'));
    // $(this).parent().parent().parent().remove();
});
}

All other functions are working properly but only this one shows error like Uncaught ReferenceError: deleteAnswer is not defined at HTMLAnchorElement.onclick . 所有其他功能均正常运行,但只有这一功能会显示错误,例如Uncaught ReferenceError: deleteAnswer is not defined at HTMLAnchorElement.onclick

Try with document.ready() 尝试使用document.ready()

$( document ).ready(function() {
    //Paste your functions inside this

}); });

or 要么

$(function() {
    //Paste your functions inside this;
});

make sure you put it into the head section of your html as follows 确保将其放入html的头部,如下所示

<head> <script type="text/javascript" src="path/to/script.js"></script> <!--other script and also external css included over here--> </head>

just replace src="path/to/script.js" with the name of your js file. 只需将src =“ path / to / script.js”替换为您的js文件的名称即可。 if its in the the same folder, you won't need to put anything but this 如果它在同一个文件夹中,则无需放置任何东西

"<script type="text/javascript" src="script.js"></script>"

again, script.js needs to be replaced with the name of your js file 再次,script.js需要替换为您的js文件的名称

deleteAnswer(uid, value) requires two parameters uid and value . deleteAnswer(uid, value)需要两个参数uidvalue

In your code, you are passing the first parameter via PHP snippet which contains an if clause to echo some value. 在您的代码中,您正在通过PHP代码段传递第一个参数,该代码段包含一个if子句以echo某些值。 What if that PHP snippet doesn't echo anything, what would happen? 如果该PHP代码段未回显任何内容,该怎么办? Exactly! 究竟! Code will break. 代码会中断。

Recommendation: Please insert else clause in your PHP snippet which should echo empty string literal . 建议:请在您的PHP代码段中插入else子句,该子句应echo empty string literal

You are welcome :) 别客气 :)

Try this code 试试这个代码

$(document).ready(function(){
    $('body').on('click','.addans',function(){
       alert('Hello Clieck me')
  })
})

https://jsfiddle.net/ta0ubp8j/3/ https://jsfiddle.net/ta0ubp8j/3/

To check actual error follow these steps: 要检查实际错误,请按照下列步骤操作:

  1. GO to the browser console of editquestion.php page(press f12 key). 转到editquestion.php页面的浏览器控制台(按f12键)。 2.write deleteAnswer("xyz",""); 2.write deleteAnswer(“ xyz”,“”); then press enter 3.if it will give same "deleteAnswer is not defined error" then there will be two case four this error otherwise it will work. 然后按回车键3。如果将出现相同的“ deleteAnswer is not defined error”,则将出现两种情况四,此错误否则将起作用。

    • your deleteAnswer function not define globally so you need to define it globally. 您的deleteAnswer函数未全局定义,因此您需要全局定义。
    • define all javascript code within $(document).ready(function(){*** your javascript code *******}) 定义$(document).ready(function(){***您的JavaScript代码*******})中的所有JavaScript代码
  2. if this will not work then check in browser console , anchor tag will not with proper deleteAnser function may be your php script breaks function syntax. 如果这不起作用,请在浏览器控制台中检查,锚标记无法正确使用deleteAnser函数,这可能是您的php脚本破坏了函数语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM