Javascript :函数语句需要一个名称

Javascript : function statement requires a name

本文关键字:一个 函数 语句 Javascript      更新时间:2023-09-26

我有一个html表格,其中有一行看起来像:

<tr>
    <td><input type="checkbox" name="check[]" value="265"></td>   
                 <td>265</td>
                    <td>NO MATCH</td>
                    <td>NO MATCH</td>
                    <td>No</td>
                    <td>0</td>
                    <td>f79a8316891</td>
              </tr>

我正在尝试构建一个 jquery 函数,该函数仅在单元格以"NO"开头时才突出显示该单元格。到目前为止,我有:

$( "td" ).hover( function() {
    var contents = $( this ).html() ;
    if (contents.match("^NO")) {
            function() {
            $( this ).append( $( "<span> ***</span>" ) );
            }, function() {
            $( this ).find( "span:last" ).remove();
            }
    }   

  });

但是我在标题中遇到了错误。我做错了什么?

你的函数在错误的地方。尝试这样的事情:

$( "td" ).hover( function() {
    var contents = $( this ).html() ;
    if (contents.match("^NO")) {
        $( this ).append( $( "<span> ***</span>" ) );
    }   
}, function() {
        $( this ).find( "span:last" ).remove();
});

jQuery悬停函数采用两个函数作为参数,第一个用于"鼠标悬停",第二个用于"鼠标退出"。您只需将这些函数放在原始代码中的错误位置即可。有关悬停的详细信息,请参阅 http://api.jquery.com/hover/

无需在悬停时添加和删除内容。只需找到所有符合您条件的单元格(使用 jQuery 的 filter()),然后给它们一个类。然后,您可以根据需要设置.nomatch元素的样式。在这里,我根据您的要求在悬停时添加了三星级文本。

$(function(){
  var key = "NO";
  var $cellsBeginWithNo = $("td").filter(function(){
    var $this = $(this);
    if($this.text().indexOf(key) === 0){ //if text begins with [key]
        $this.addClass("nomatch");       //give it a class
        return $this;                    //add it to our collection
    }
    return false;
  });
  /* 
    Now you have a jQuery collection of matched elements that you can apply further functions to if you like. EG: 
    $cellsBeginWithNo.on("click", function(){alert("click");});
  */
});
td.nomatch {
    background-color:#ffeeee;
}
td.nomatch:hover:after {
    content : " ***";
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
    <tr>
        <td><input type="checkbox" name="check[]" value="265"></td>   
        <td>265</td>
        <td>NO MATCH</td>
        <td>NO MATCH</td>
        <td>No</td>
        <td>0</td>
        <td>f79a8316891</td>
    </tr>
</table>