使用jquery附加父标记的属性

时间:2018-02-07 23:07:41

标签: javascript jquery html

我有一些看起来像这样的HTML:

<div>
    <strong>
        <a href="link.php?category=1&link=apple">
            <span>string</span>
        </a>
    </strong>
</div>

<div>
    <strong>
        <a href="link.php?category=2&link=banana">
            <span>string</span>
        </a>
    </strong>
</div>

我想在每个div中添加一个包含&#34; string&#34;的span的链接。该链接将id作为包含span的链接的href属性的link参数,例如:

<div>
    <strong>
        <a href="link.php?category=1&link=apple">
            <span>string</span>
        </a>
    </strong>
    <a class="details" id="apple_details">Show Details +</a>
</div>

<div>
    <strong>
        <a href="link.php?category=2&link=banana">
            <span>string</span>
        </a>
    </strong>
    <a class="details" id="banana_details">Show Details +</a>
</div>

到目前为止我所拥有的是:

$("span:contains('string')").parent().parent().parent().append('<a class="details" id="details">Show Details +</a>');

如何获取链接的href属性?

2 个答案:

答案 0 :(得分:3)

使用.each()遍历所有跨距,获取父级的属性,然后附加到DIV。

$("span:contains('string')").each(function() {
    var href=$(this).parent().attr("href");
    var link = href.match(/&link=([^&]+)/)[1];
    $(this).closest("div").append($("<a>", {
        "class": "details",
        id: link + "_details",
        text: "Show Details"
    }));
});

答案 1 :(得分:1)

&#13;
&#13;
ko.components.register('DefaultCellTemplate', {
  template: '<span data-bind="text: $data"></span>'
});
&#13;
$("a[href*='link=']").each(function() {
  if( $(this).text() !== "string" ) return; // Do nothing.
  var id = $(this).attr("href").match(/[?&]link=([^&]+)/)[1];
  if( id ) $(this).closest("div").append(`<a class="details" id="${id}_details">Show Details +</a>`);
});
&#13;
&#13;
&#13;