目前我正在使用这个结合php的jquery脚本(无所谓):
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
var select = "<?php if_exist($select, ''); ?>";
var event = "<?php if_exist($event, 'click'); ?>";
var display = "<?php if_exist($display, '#display'); ?>";
var loading = "<?php if_exist($loading, '#loading'); ?>";
var datatype = "<?php if_exist($datatype, 'json'); ?>";
var cache;
if (event == "submit"){ $("input:submit").hide(); }
$(select).bind( event , function(key){
if ( event == "keypress" ) {
if ( key.which == <?php if_exist($keycode, '13'); ?> ) {
$(loading).show();
$.post(
$(select).attr("action"),
$(select).serialize(),
function(data){
if (datatype == "html" || datatype == "text"){ var returned = data; }
if (datatype == "json"){ var returned = data<?php if_exist($return, '.return'); ?>; }
if (returned != cache)
{
cache = returned;
if (datatype == "html" || datatype == "text"){ $(display).hide().html(data).fadeIn(); }
if (datatype == "json"){ $(display).hide().autoRender(data).fadeIn(); }
$(loading).hide();
}
},
datatype
);
return false;
};
}
else
{
$.post(
$(select).attr("action"),
$(select).serialize(),
function(data){
if (datatype == "html" || datatype == "text"){ var returned = data; }
if (datatype == "json"){ var returned = data<?php if_exist($return, '.returnValue'); ?>; }
if (returned != cache)
{
cache = returned;
if (datatype == "html" || datatype == "text"){ $(display).hide().html(data).fadeIn(); }
if (datatype == "json"){ $(display).hide().autoRender(data).fadeIn(); }
$(loading).hide();
}
},
datatype
);
if ($event == 'submit') { return false;}
}
});
});
</script>
我想减少此脚本中使用的代码量,我认为我们可以通过注意包含if ( event == "keypress" ) {
的第11行来确保减少此脚本中的代码量,因为在下一个else
语句相同的代码重复两次,但我们怎么做呢?有什么想法吗?
答案 0 :(得分:1)
以下内容看起来重复:
$.post(
$(select).attr("action"),
$(select).serialize(),
function(data){
if (datatype == "html" || datatype == "text"){ var returned = data; }
if (datatype == "json"){ var returned = data; }
if (returned != cache)
{
cache = returned;
if (datatype == "html" || datatype == "text"){ $(display).hide().html(data).fadeIn(); }
if (datatype == "json"){ $(display).hide().autoRender(data).fadeIn(); }
$(loading).hide();
}
},
datatype
);
你应该考虑将它的功能转移到一个功能(原文如此)!
答案 1 :(得分:1)
除了Vlad的回答:删除不必要的if查询和变量赋值:
$.post(
$(select).attr("action"),
$(select).serialize(),
function(data) {
// in every case, data is assigned to another variable which is
// unnecessary as well
// if (datatype == "html" || datatype == "text"){ var returned = data; }
// if (datatype == "json"){ var returned = data; }
if (data != cache) {
cache = data;
}
if (datatype == "html" || datatype == "text") {
$(display).hide().html(data).fadeIn();
}
else if (datatype == "json"){
$(display).hide().autoRender(data).fadeIn();
}
$(loading).hide();
}
}, datatype );