原因:
由於default position是CClientScript::POS_READY
,生成的JS是:
jQuery(function($) {
// ... there could be some other yii scriptlets too ...
function jobTitle(e) {
alert('e');
}
});
這意味着你的功能jobTitle
僅可在jQuery();
功能範圍之內,而不是從外面,這就是爲什麼你的未定義錯誤。
解決方案1:
如果你使用的位置:CClientScript::POS_HEAD
或CClientScript::POS_BEGIN
或CClientScript::POS_END
與registerScript
通話,即:
Yii::app()->clientScript->registerScript('jobTitle', "
function jobTitle(e) {
alert('e');
}
", CClientScript::POS_END);
的功能將被外界定義,並在全球範圍內,然後你就可以使用該功能。
解決方案2:
另外,如果你需要內ready()
功能,內jQuery(function($){});
也就是說,你可以定義全局窗口對象的功能,並且還從外部訪問:
Yii::app()->clientScript->registerScript('jobTitle', "
window.jobTitle = function jobTitle(e) {
alert('e');
}
");
解決方案3:
或者你可以簡單地從jQuery的本身添加事件處理程序,代替鄰f在html中內聯:
Yii::app()->clientScript->registerScript('jobTitle', "
$('body').on('change', 'id-of-job-title-input', function(e){
console.log(e);
});
");