如何在jquery方法中创建一个if语句

How to make an if statement in jquery method

本文关键字:一个 语句 if 创建 jquery 方法      更新时间:2023-09-26
    .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 Autofill widget。我希望自动完成文本输入来建议项目的"parent_term_id"等于某物,否则什么也不建议。(这是Wordpress(

但是,如果语句不起作用。知道吗?

.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 );
});

你在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。

有时,放置一些警报以查看代码中断的位置会很有帮助。此外,如果您认为 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>" );
}
相关文章: