jQuery选择器匹配确切的值

时间:2017-06-01 21:27:23

标签: javascript jquery

我正在尝试选择包含变量的td,所以我现在所做的就是:

$('td:contains('+ splitDate[0] + ')').empty().append(
    '<div class="ex-half-done ex-base">' + splitDate[0] +'</div>'
);

但在此示例中,splitDate[0]为“1”,因此现在它选择包含“1”的每个td

但是,如果它与splitDate[0]的确切值相匹配,而不是append <div class="ex-half-done ex-base">

,我想做什么?

我该怎么做?我已经找到像jQuery的filter()这样的东西:

var $results = $('td').find(splitDate[0]).filter(function()
    return $(this).text() === splitDate[0];
});
console.log('result', $results);

$results.css('color', 'red');
$results.empty().append('<div class="ex-done ex-base">' + splitDate[0] +'</div>');     

但这会让我回复td

这是td元素的示例:

<td _ngcontent-c1="" tappable="" class="monthview-selected monthview-current" ng-reflect-ng-class="monthview-selected monthview-c">
  <!--bindings={"ng-reflect-ng-template-outlet": "[object Object]",
  "ng-reflect-ng-outlet-context": "[object Object]"
}-->2 </td>

图片enter image description here

console.log('check', splitDate[0]) = check 1

的一个例子

1 个答案:

答案 0 :(得分:1)

尝试:

var $results;
$('td').each(function(){
  if($(this).html() == splitDate[0]){
    $results = $(this);
  }
});
console.log('result', $results);
$results.css('color', 'red');
$results.empty().append('<div class="ex-done ex-base">' + splitDate[0] +'</div>');  

这将确保它完全匹配。

或少一点代码:

$('td').each(function(){
  if($(this).html() == splitDate[0]){
    $(this).empty().css('color', 'red').append('<div class="ex-done ex-base">' + splitDate[0] +'</div>');
  }
});

您想知道MORE吗?

<强>更新

根据您的示例,我有一个分享的工作示例:

https://jsfiddle.net/Twisty/ugrw8hjb/

<强> HTML

<table>
  <tr>
    <td _ngcontent-c1="" tappable="" class="monthview-selected monthview-current" ng-reflect-ng-class="monthview-selected monthview-c"> 1 </td>
    <td _ngcontent-c1="" tappable="" class="monthview-selected monthview-current" ng-reflect-ng-class="monthview-selected monthview-c"> 2 </td>
    <td _ngcontent-c1="" tappable="" class="monthview-selected monthview-current" ng-reflect-ng-class="monthview-selected monthview-c"> 3 </td>
    <td _ngcontent-c1="" tappable="" class="monthview-selected monthview-current" ng-reflect-ng-class="monthview-selected monthview-c"> 4 </td>
    <td _ngcontent-c1="" tappable="" class="monthview-selected monthview-current" ng-reflect-ng-class="monthview-selected monthview-c"> 5 </td>
  </tr>
</table>

<强> JS

var splitDate = [2, 1, 2017];
$(function() {
  $('td').each(function() {
    if ($(this).text().trim() == splitDate[0].toString()) {
      $(this).empty().css('color', 'red').append('<div class="ex-done ex-base">' + splitDate[0] + '</div>');
    }
  });
});

因为内容类似于&#34; 2&#34;,您可能希望使用.trim()删除空格。这将有助于确保&#34; 2&#34; ==&#34; 2&#34;,原因&#34; 2&#34; !=&#34; 2&#34;。此外,根据您的其他更新,您似乎有一个整数数组。您将需要使用.toString()来帮助比较字符串与字符串。