contenteditable - 使用 jquery 更新 data-* 属性

contenteditable - updating data-* attributes using jquery

我正在为使用 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>

结果是:

如何 add/update data-* 属性?

Using the data() method to update data does not affect attributes in the DOM. To set a data-* attribute value, use attr.

因此,对于 add/update,您使用 .attr(attribute, value):

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

Since jQuery 1.4.3, data-* attributes are used to initialize jQuery data. An element's data-* attributes are retrieved the first time the data() method is invoked upon it, and then are no longer accessed or mutated (all values are stored internally by jQuery).

Referece