如何使用数据标签向我的标头添加锚跳标签?

时间:2016-06-09 03:54:44

标签: javascript jquery html anchor

我试图让这更通用,不确定如何使用数据标签...

我的标题包含< a>锚标签看起来像这样:

<h4>Prohibited items<a class="anchor" id="prohibited-items" href="#prohibited-items" onclick="$('#prohibited-items').ScrollTo();"></a></h4>

我想要我的&lt; h4&gt;标题看起来像这样:

<h4 data-anchor="prohibited-items">Prohibited items</h4>

如何动态地将锚标签注入所有&lt; h4&gt;包含data-anchor标签?

更新:这是我最终做的(现在使用jQuery 3):

// Generate anchor tags where data-anchor data tag is used
// if data-anchor does not have a value the element text will be used to generate the anchor id
// for example: <h4 data-anchor>Sample title</h4> or <h4 data-anchor="custom-id">Sample title</h4>
$("[data-anchor]").each(function () {
    var text = $(this).text();
    var id = $(this).attr("data-anchor"); // Check if a custom id was provided
    if (id != null && id.replace(/ /g, "") === "") {
        id = text.replace(/[^\w\s]/gi, "-"); // Remove special characters
        id = id.replace(/ /g, "-").toLowerCase(); // Replace spaces with "-"
    }
    if (!$(this).hasClass("cursor-pointer"))
        $(this).addClass("cursor-pointer");
    // console.log("id = " + id + ", text = " + text);
    $(this).attr("onclick", "$('html, body').stop().animate(" +
        "{ scrollTop: $('#" + id + "').offset().top }, '400', 'swing'); " +
        "document.location='#" + id + "'; return false;");
    $(this).html("<div class='anchor-space'>" + text + "</div><a " +
        "class='anchor-marker no-print' " +
        "id='" + id + "' " +
        "href='#" + id + "' " +
        "></a><span " +
        "class='anchor-symbol no-print'" +
        "></span>");
});

.anchor-marker {
top: -110px;
position: relative;
display: block;
}
.anchor-space {
    margin-right: 30px;
}
.anchor-symbol {
    float: right;
    margin-top: -30px;
    &:before {
        font-family: "FontAwesome";
        content: "\f13d"; // http://fontawesome.io/icon/anchor/
        float: right;
    }
}

3 个答案:

答案 0 :(得分:0)

尝试:

$("h4[data-anchor]").on('click', function(){
 var anchorElement = $(this).data("anchor");
 $(anchorElement).scrollTo();
}

答案 1 :(得分:0)

您可以使用以下内容:

将“禁止的项目”文字放在范围内,如

<h4><span>Prohibited items</span><a class="anchor" id="prohibited-items" href="#prohibited-items" onclick="$('#prohibited-items').ScrollTo();"></a></h4>

jayascript代码如下:

$(document).ready(function(){
       $('h4').each(function(){
         $(this).data('anchor',$(this).find('span').text());
       });
});

希望这会有所帮助。

答案 2 :(得分:0)

尝试以下

$('[data-anchor]').click(function(){
  var id = $(this).attr('data-anchor');
  $(id).scrollTo();
});

或:

$('[data-anchor]').each(function() {
  var text = $(this).text();
  var id =$(this).attr('data-anchor');
  $(this).html(text+'<a class="anchor" id="'+id.substring(1)+'" href="'id'" onclick="$('+id+').ScrollTo();"></a>')
});