[英]How to make a link out of text on the fly? — JQuery beginner
我在頁面上有一堆:
<div class="item" id="555">
<div class="wrapper>
<p>Make Link One</p>
</div>
<p class="action">Make Link Two</p>
</div>
如何根據ID 555動態建立2個文本鏈接? 即。 它們都應該是http://555
鏈接
有一個獨特的業務需求,這就是為什么它們不只是普通的hrefs的原因。
您可以將click事件處理程序綁定到使用其自身ID重定向用戶的包含div:
$('.item').on('click', function () {
window.location = 'http://' + this.id;
});
如果容器元素內還有其他內容不應該觸發重定向,則可以綁定到容器內的<p>
元素:
$('.item').on('click', 'p', function () {
window.location = 'http://' + $(this).parents('.item:first')[0].id;
});
順便說一句,ID不能以數字開頭。 這是指向ID正確語法的鏈接: HTML中id屬性的有效值是什么?
請注意, .on()
是jQuery 1.7中的新增功能。 在第一個示例中,它替換了已貶值的.bind()
,在第二個示例中,它替換了已貶值的.delegate()
。
$('p').each(function(){
var $this = $(this);
var href = $this.parents('.item:first')[0].id;
$this.wrap('<a href=http://"' + href + '">');
});
.each
遍歷找到的p
元素。 然后,它通過類.item
( $this.parents('.item:first')
)查找父級以獲取ID。 [0]
部分將jQuery對象變成一個標准的DOM元素,以便我們可以輕松地從該元素中獲取id
屬性(您也可以完成$this.parents('.item:first').attr('id')
堅持使用純jQuery)。 最后,我們將p
包裝在帶有正確href
的錨標記中。
$(document).ready(function(){
$(".item p").each(function(){
var t1 = $(this).text();
var linkid = $(this).parents('.item:first').attr("id");
$(this).parent().append('<a href="http://' + linkid + '">' + t1 + '</a>');
$(this).remove();
});
});
我會這樣做,假設您希望將其應用於作為item
類元素的子元素的每個p
:
$(function(){
$('.item p').each(function(){
var $this = $(this);
$this.contents().wrap($('<a>', { href: $this.closest('.item').attr('id') }));
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.