我已下载此脚本以使用表单中的条件字段:
(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
。
我已将脚本包含在标头标记中,并且我在主体底部使用此脚本调用它:
<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
答案 0 :(得分:0)
我找到了解决方案。
因为任何原因,$ object和jQuery对象在我的代码中是不一样的。
我在浏览器控制台上发现了它:
$===jQuery
这个返回false(这是因为在其他JS中,我使用了noConflict()
,这给了我问题)
说明:noConflict()
所以我已经解决了它改变我的JS的最后一行:
//Show based on current value on page load
$.fn.showOrHide(eval(cond), $section);
});
}
}($));
使用$
代替'jQuery'