【问题标题】:How to target tag a inside div with this?如何用这个来标记内部 div?
【发布时间】:2015-06-11 08:04:03
【问题描述】:
<c:forEach items="${list}" var="item">
    <div class="block" id="${item.id}" data-num="${item.itemRead}">
        <a id="${item.id}"
            href="javascript:showFeedItem('${item.id}','${item.itemRead}');">
    </div>
</c:forEach>

为什么我在创建新的数据属性data-num时有未定义的属性名称data-num? jQuery:

     $(document).ready(function(){
            $('.block').each(function(i, obj) {
                if($(this).attr("data-num")=="0"){
                   //need to style a inside this
                    $(this).css("background-color","black");
                }
            });
        });

如何像这样定位a

 $('.block[id="' + id + '"] a').css('color', 'black');

但使用$(this).css("background-color","black");

【问题讨论】:

  • $('a', this).css("background-color","black");

标签: javascript jquery css jsp loops


【解决方案1】:

this 作为上下文传递给 jQuery 选择器

$(document).ready(function () {
    $('.block').each(function (i, obj) {
        if ($(this).attr("data-num") == "0") {
            //need to style a inside this
            $('a', this).css("background-color", "black");
            //or $(this).find('a').css("background-color", "black");
        }
    });
});

您也可以将其缩短为

$(document).ready(function () {
    $('.block[data-num="0"] a').css("background-color", "black");
});

【讨论】:

  • 为什么新建数据属性data-num时属性名data-num未定义?
  • @RuslanLomov 对不起,你是什么意思
  • 感谢您的回答。创建新数据 data-num="${item.itemRead}"
【解决方案2】:

如果您想获取this 的直系后代(就像在您的代码中一样),您可以使用.children() 方法。

$(this).children(a).css("background-color","black");

【讨论】:

    【解决方案3】:

    我猜你需要改变这个:

    <c:forEach items="${list}" var="item">
        <div class="block" id="${item.id}" data-num="${item.itemRead}">
            <a href="javascript:showFeedItem('${item.id}','${item.itemRead}');">
        </div>
    </c:forEach>
    

    从锚点中删除了id="${item.id}"。在我看来,您正在为单个页面中的不同项目添加相同的 ID,但每个元素必须是唯一的。

    现在在 js 中你必须使用 .find() 来设置锚点的样式并设置它的样式:

    $(document).ready(function(){
        $('.block').each(function(i, obj) {
            if($(this).attr("data-num")=="0"){ // or if($(this).data("num")=="0"){
                $(this).find('a').css("background","black");
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      相关资源
      最近更新 更多