如何在飞行中用文本创建链接?——JQuery初学者
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
有一个独特的业务需求,这就是为什么它们一开始就不仅仅是正常的href。
您只需将点击事件处理程序绑定到包含的div,该div使用自己的ID重定向用户:
$('.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 + '">');
});
CCD_ 6循环通过所找到的CCD_。然后,它通过类.item
($this.parents('.item:first')
(查找父iwth来获取id。[0]
部分将jQuery对象变成一个标准DOM元素,这样我们就可以很容易地从该元素中获取id
属性(您也可以使用$this.parents('.item:first').attr('id')
来坚持纯jQuery(。最后,我们用正确的href
将p
封装在锚标签中。
$(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();
});
});
我会这样做,假设您希望它应用于每个p
,它是具有item
类的元素的子元素:
$(function(){
$('.item p').each(function(){
var $this = $(this);
$this.contents().wrap($('<a>', { href: $this.closest('.item').attr('id') }));
});
});
相关文章:
- 如何使用jQuery自动打开页面上的所有链接
- 如何在不链接/jquery的情况下使用方法应用css属性数组
- 干净地链接 jQuery ajax 请求
- 在coffeescript中链接jquery方法和参数
- 如何正确链接JQuery并使用.getJSON
- 链接jQuery中的两个元素
- 滚动到活动链接 jQuery
- 如果链接少于 1 个,则计数和隐藏链接.Jquery.
- 获取链接 href 并将其应用于另一个链接 jQuery
- jQuery-检查复选框值(链接jQuery函数与If Statment)
- 在具有固定链尾调用的循环中链接jquery.when().then()
- 更改链接jquery的href
- 使word in变成一个链接jQuery
- 如何在飞行中用文本创建链接?——JQuery初学者
- 检测文本中的超链接- jQuery
- 我如何从现有的第三方控件链接jQuery事件
- 链接JQuery命令
- 如何在点击链接Jquery/JS时将动态内容添加到引导模式中
- 切换单击链接jquery时不关闭
- 如何知道点击了哪个链接[jQuery]