如何通过 jQuery 将文本从 span 标签添加到 data-attr? [英] How to add text from span tag to data-attr by jQuery?

查看:30
本文介绍了如何通过 jQuery 将文本从 span 标签添加到 data-attr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 span 标签中的文本添加到 data-attr?

How to add text from span tag to data-attr?

示例:
我有这个代码

Example:
I have this code

<div class="clearfix colelem" id="u92-5"><!-- content -->
     <p>Icon<span id="u92-2">iconsymbol</span></p>
    </div>

我想将 iconsymbol 添加到相同元素的 data-attr="iconsymbol" 中,例如:

And I want to add iconsymbol to data-attr="iconsymbol" of the same element like a:

<div class="clearfix colelem" id="u92-5" data-attr="iconsymbol"><!-- content -->
         <p>Icon<span id="u92-2">iconsymbol</span></p>
        </div>

是的,它适用于所有具有 title="icon"

Yes and it will be with all elements which has a title="icon"

<script>	
    $( document ).ready(function() {
	    $("[title*='icon']").attr('data-attr',function(){ 
   // I don't know
        }).removeAttr('title');
    });
</script>

你知道怎么做吗?所以我知道这很简单,但我是 jquery 的新手,我需要你的帮助.
希望你能理解我的问题.

Do you know how to do it? So I know it is very simple but I am new in jquery and I need in your help.
I hope you understood my question.

推荐答案

这是一个适合您的示例.可能有几种方法可以解决这个问题,但这应该可以帮助您入门.请参阅随附的 JSFiddle 以查看此示例的实际效果

Here is an example that should work for you. There is probably a few ways you can pull this off, but this should hopefully get you started. Please see the attached JSFiddle to see this example in action

$(function() {
    $('[title*="icon"] span').each(function(){
        $(this).parent().closest('div').attr('data-attr', $(this).text())
    });
});

这也是你可以做到这一点的另一种方法

Here is another way you can do this as well

$('[title*="icon"]').each(function(){
    $(this).attr('data-attr', $(this).children().closest('span').text());
});

这篇关于如何通过 jQuery 将文本从 span 标签添加到 data-attr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆