如何通过jQuery将跨度标签中的文本添加到数据属性中? [英] How to add text from span tag to data-attr by jQuery?
问题描述
如何将文本从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将跨度标签中的文本添加到数据属性中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!