[英]jQuery script works only once, then TypeError: $(…) is not a function
我已下載此腳本以在表單中使用條件字段:
(function ($) {
$.fn.conditionize = function(options) {
var settings = $.extend({
hideJS: true
}, options );
$.fn.showOrHide = function(is_met, $section) {
if (is_met) {
$section.slideDown();
}
else {
$section.slideUp();
$section.find('select, input').each(function(){
if ( ($(this).attr('type')=='radio') || ($(this).attr('type')=='checkbox') ) {
$(this).prop('checked', false).trigger('change');
}
else{
$(this).val('').trigger('change');
}
});
}
}
return this.each( function() {
var $section = $(this);
var cond = $(this).data('condition');
// First get all (distinct) used field/inputs
var re = /(#?\w+)/ig;
var match = re.exec(cond);
var inputs = {}, e = "", name ="";
while(match !== null) {
name = match[1];
e = (name.substring(0,1)=='#' ? name : "[name=" + name + "]");
if ( $(e).length && ! (name in inputs) ) {
inputs[name] = e;
}
match = re.exec(cond);
}
// Replace fields names/ids by $().val()
for (name in inputs) {
e = inputs[name];
tmp_re = new RegExp("(" + name + ")\\b","g")
if ( ($(e).attr('type')=='radio') || ($(e).attr('type')=='checkbox') ) {
cond = cond.replace(tmp_re,"$('" + e + ":checked').val()");
}
else {
cond = cond.replace(tmp_re,"$('" + e + "').val()");
}
}
//Set up event listeners
for (name in inputs) {
$(inputs[name]).on('change', function() {
$.fn.showOrHide(eval(cond), $section);
});
}
//If setting was chosen, hide everything first...
if (settings.hideJS) {
$(this).hide();
}
//Show based on current value on page load
$.fn.showOrHide(eval(cond), $section);
});
}
}(jQuery));
我正在嘗試執行此操作是因為我需要在其中一個選項卡中使用conditionize(),並且當我重新加載該選項卡時,所有功能都可以使用,但是如果我轉到其他選項卡並返回到上一個選項卡(需要該功能的地方),得到那個錯誤。
更改標簽時,我只會重新加載頁面的一部分。
當我加載頁面時,這是完美的,但是如果我嘗試從瀏覽器控制台再次調用函數,它會告訴我TypeError: $(...)conditionize() is not a function
。
我已將該腳本包含在header標簽中,並使用此腳本在正文底部對其進行了調用:
<script type="text/javascript">
$('.conditional').conditionize();
</script>
編輯:
我已經寫了
<script type="text/javascript">
console.log($('.conditional').conditionize);
setTimeout(function () {console.log($('.conditional').conditionize);}, 2);
</script>
這會在控制台上顯示我的功能,並且經過2毫秒后,我會undefined
打印我
我找到了解決方案。
由於任何原因,$對象和jQuery對象在我的代碼中都不相同。
我在瀏覽器控制台上使用它發現了它:
$===jQuery
返回false(這是因為在其他JS中,我使用的是noConflict()
,這給我帶來了問題)
說明: noConflict()
所以我通過以下方法解決了更改JS最后一行的問題:
//Show based on current value on page load
$.fn.showOrHide(eval(cond), $section);
});
}
}($));
用$
代替'jQuery'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.