我在调用外部js文件的onclick按钮期间遇到问题,我没有定义onclick函数的错误。
<table class="table table-striped table-bordered table-nonfluid" style='width: auto;'>
<tr>
<td>Name: </td>
<td><input type='text' name='ref_name' id='ref_name'></td>
</tr>
<tr>
<td>Description: </td>
<td><input type='text' name='ref_desc'></td>
</tr>
<tr>
<td colspan='2' align='right'><button type='button' class='btn btn-primary' id="btn_save" onclick="saveMst();">Save</button></td> //this is the line onclick "saveMst()" is not defined when calling external js file.
<input type='hidden' name='ref_type' value='1'>
</tr>
</table>
这是我在php中定义的脚本:
$scripts = '<script type="text/javascript" src="js/references.js"></script>';
$smarty->assign('script', $scripts);
以下是references.js代码
function saveMst(){
sessionExpired();
if(mstValidate()==true){
var url= "ref_deparment.php?do=save&save=mst&ref_name="+encodeURIComponent(ref_name)+
"&ref_desc="+encodeURIComponent(ref_desc);
alert (url);return false;
topMsgDisplay('Saving... Please wait...');
var myAjax = new Ajax.Request(url, { method: 'get', onComplete: function(oR){
hideOverlay();
r = oR.responseText.split('||');
//alert (oR.responseText);
if(r[0]==1) {
$('btn_save').style.display = 'none';
alert('Record had been save sucessfully!');
getEdit(r[1]);
}
else alert(r[1]);
} });
}
}
function mstValidate(){
borderpass = '1px solid #ccc';
borderfail = '1px solid #f00';
shortdesc = $('ref_name').value;
longdesc = $('ref_desc').value;
err_msg = 'You\'ve encounter the below error:\n';
pass=true;
if(shortdesc.length==0){
pass=false;
err_msg += '* Name field is left empty.\n';
$('ref_name').style.border = borderfail;
}else {
$('ref_name').style.border = borderpass;
}
if(longdesc.length==0){
pass=false;
err_msg += '* Description field is left empty.\n';
$('ref_desc').style.border = borderfail;
}else {
$('ref_desc').style.border = borderpass;
}
if(pass==false){
alert(err_msg);
return false;
}else return true;
}
答案 0 :(得分:0)
您可以将事件处理程序从内联html移动到您的javascript文件。你应该把它放在一个块中,该块在加载DOM时执行,这样你就可以确定所有要附加处理程序的元素都存在。
当你似乎使用jquery时,它看起来像是:
$(function(){
// Document ready
$('#btn_save').on('click', function() {
saveMst();
});
});