我试图选择一个包含变量的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>


这里的图片javascript - 匹配确切值的jQuery选择器-LMLPHP

还有console.log('check', splitDate[0]) = check 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>');
    }
  });
});


由于内容类似“ 2”,您可能要使用.trim()删除空格。这将有助于确保“ 2” ==“ 2”,导致“ 2”!=“ 2”。另外,根据您的其他更新,您似乎有一个整数数组。您将要使用.toString()来帮助比较字符串。

09-19 12:16