如何使用属性并将其作为元素插入 jquery

How to use attribute and insert it as element jquery

是否可以插入,f.e。到 "span",像这样的属性。

<span data-text="Hello world"></span>

如果事件达到其条件,则脚本从 "data-text" 获取信息并将其插入 "span"。

因此,生成的跨度将类似于

<span data-text="Hello world">Hello world</span>

是的,您可以使用 text 如下

$('span[data-text]').text(function() {
    return $(this).data('text');
});
  1. $('span[data-text]') 将 select 所有具有 data-text 属性的 <span> 元素
  2. text() with callback function 用于遍历所有匹配的元素并更新它们各自的 innerText。您也可以使用 html() 而不是 text().
  3. $(this).data('text') 将检索当前 ($(this)) 元素的 data-text 属性值并从函数返回它会更新 innerText。

演示

$('span[data-text]').text(function() {
  return $(this).data('text');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<span data-text="Hello world"></span>
<span data-text="GoodBye World!"></span>
<span data-text="Is it Working?"></span>