未添加到元素的类

时间:2014-10-24 11:34:06

标签: jquery

我无法弄清楚为什么没有将类添加到选定的td元素中。

jQuery DatePicker表中的日期单元格示例...

<td class=" " data-handler="selectDay" data-event="click" data-month="9" data-year="2014">
    <a class="ui-state-default" href="#">1</a>
</td>

我正在尝试使用jQuery ...

<script>

    var dateList = [ 1, 10, 2014 ];

    $("td[data-month='" + dateList[1] + "'][data-year='" + dateList[2] + "']")
        .filter(function() {
            return $(this).text() === dateList[0];
        }).addClass("cal-selected-date");

</script>

有什么建议吗?谢谢。

2 个答案:

答案 0 :(得分:2)

您需要在filter

中返回结果
return $(this).trim() === dateList[0];

编辑:

由于您没有选择a而是选择td,因此您还需要添加.trim()来修剪空白。 最后但并非最不重要的是,您需要将两者都转换为数字或删除单个=

return $(this).text().trim() == dateList[0];

return Number($(this).text().trim()) === dateList[0];

答案 1 :(得分:1)

您错过了return

$("td[data-month='" + dateList[1] + "'][data-month='" + dateList[2] + "']")
    .filter(function() {            
        return $(this).text() === dateList[0];
    }).addClass("cal-selected-date");

或者,您可以在过滤器中使用。data()

$("td")
    .filter(function() {
        return
            $(this).data('month') == dateList[1] &&
            $(this).data('year') == dateList[2] &&
            +$(this).text() === dateList[0]; //Convert text to number using +
    }).addClass("cal-selected-date");
相关问题