How to add text from span tag to data-attr by jQuery?(如何通过 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="aWNvbg=="
Yes and it will be with all elements which has a title="aWNvbg=="
<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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何通过 jQuery 将文本从 span 标签添加到 data-attr?


- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07