.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
if ( ( item.parent_term_id == "16" ) ) {
.append( "<a>" + (item.child_term ? item.child_term : + "") + "</a>" )
}
.appendTo( ul );
};
此代码属于JqueryUi自动完成小部件。我希望自动完成文本输入建议项目,如果他们的“parent_term_id”等于某事,否则建议什么。 (这是Wordpress)
但if语句不起作用。有什么想法吗?
答案 0 :(得分:5)
.data( "autocomplete" )
._renderItem = function( ul, item ) {
var $li = $( "<li></li>" );
$li.data( "item.autocomplete", item );
if ( ( item.parent_term_id == "16" ) ) {
$li.append( "<a>" + (item.child_term ? item.child_term : + "") + "</a>" );
}
return $li.appendTo( ul );
});
如果必须在一行上执行此操作(尽管这样做没有意义):
.data( "autocomplete" )
._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.filter(function () {
return item.parent_term_id == "16";
})
.append( "<a>" + (item.child_term ? item.child_term : + "") + "</a>" )
.end()
.appendTo( ul );
});
答案 1 :(得分:4)
你在jQuery代码中看到的无穷无尽的链接并不总是最好的做法。
在这里你最好使用变量:
.data( "autocomplete" )._renderItem = function( ul, item ) {
var li = $( "<li></li>" );
li.data( "item.autocomplete", item );
if ( ( item.parent_term_id == "16" ) ) {
li.append( "<a>" + (item.child_term ? item.child_term : + "") + "</a>" );
}
li.appendTo( ul );
return li;
};
你可以组合其中的一些,但对于if
,你必须停止进行链式函数调用,这意味着使用var。
答案 2 :(得分:2)
有时将一些警报放入以查看代码中断的位置是有帮助的。此外,如果您认为if块未被调用,您可以尝试简化它或反转逻辑。 IE
alert("precondition");
if ( ( item.parent_term_id == "16" ) ) {
alert("in if block!");
li.append( "<a>" + (item.child_term ? item.child_term : + "") + "</a>" );
}
简化
alert("precondition");
if ( ( item.parent_term_id) ) {
alert("in if block!");
li.append( "<a>" + (item.child_term ? item.child_term : + "") + "</a>" );
}
逆逻辑
alert("precondition");
if ( ( item.parent_term_id != "16") ) {
alert("in if block!");
li.append( "<a>" + (item.child_term ? item.child_term : + "") + "</a>" );
}