【问题标题】:contenteditable - updating data-* attributes using jquerycontenteditable - 使用 jquery 更新 data-* 属性
【发布时间】:2019-07-26 16:23:23
【问题描述】:

我正在为使用contenteditable 的客户端构建一些基本的富文本编辑功能。其中一项功能需要更改按钮的data-* 属性的值,例如<button data-type="telephone">Text</button>

我在下面创建了一个最小示例 - 这将创建一个 contenteditable 区域,然后 jquery 尝试更新 <button>,然后将更新的 HTML 打印到 #output div。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>contenteditable data-* test</title>
</head>
<body>

<div id="input" contenteditable>
  <p>Some text!</p>
  <button data-url="/go-somewhere">Button text!</button>
  <p>More text!</p>
</div>

<hr>

<div id="output" style="font-family: monospace;">
</div>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

<script>
$(document).ready( function(){

  // --- Update the button --- //

  // 1. Add new data attribute: data-new="test!"
  $( '#input button' ).data( 'new', 'test!' );

  // 2. Update existing data attribute: data-url="/somewhere-else"
  $( '#input button' ).data( 'url', '/somewhere-else' );

  // 3. Add a class
  $( '#input button' ).addClass( 'new-class' );

  // --- Display the updated content --- //

  $( '#output' ).html( 
    $( '#input' ).html().replace( /</g, '&lt;' ).replace( />/g, '&gt;' ) 
  );
});
</script>

</body>
</html>

结果是:

  • jquery 未能添加新的data-new="test!" 属性
  • jquery 未能更新现有的data-url 属性
  • jquery 是否设法使用 addClass() 添加class="new-class"

如何添加/更新 data-* 属性?

【问题讨论】:

    标签: jquery html contenteditable custom-data-attribute


    【解决方案1】:

    使用data()方法更新数据不会影响属性 DOM。要设置 data-* 属性值,请使用 attr。

    所以,要添加/更新,您使用.attr(attribute, value)

    $( '#input button' ).attr( 'data-new', 'test!' );
    $( '#input button' ).attr( 'data-url', '/somewhere-else' );
    

    从 jQuery 1.4.3 开始,data-* 属性用于初始化 jQuery 数据。第一次检索元素的 data-* 属性 data() 方法在其上被调用,然后不再被访问或 变异(所有值都由 jQuery 内部存储)。

    Referece

    【讨论】:

    • 啊,是的,当然!很明显,我因为没有早点想到它而自责...谢谢@azametzin
    • ...虽然刚刚发现第二行应该读为$( '#input button' ).attr( 'data-url', '/somewhere-else' ); - attr() 的第一个参数缺少'data-'前缀:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 2017-06-30
    相关资源
    最近更新 更多