且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何更新现有的Bootstrap模态数据目标?

更新时间:2023-12-02 21:56:10

让我们看看jQuery documetation中的.data()是什么:

Let's look in the jQuery documetation what .data() is:

.data()

存储与匹配元素关联的任意数据,或者在匹配的元素集中的第一个元素的命名数据存储处返回值.

.data()

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

说明:存储与匹配元素关联的任意数据.

Description: Store arbitrary data associated with the matched elements.

  • key

类型:String

一个字符串,命名要设置的数据.

A string naming the piece of data to set.

类型:对象

新数据值;它可以是任何Javascript类型,包括数组或对象.

The new data value; it can be any Javascript type including Array or Object.


使用$('#testButton').data('target','#testModal2'),您将修改data-target属性,但会将字符串"#testModal2"存储在"target"字段中.然后$('#testButton').data('target')将返回"#testModal2".


Using $('#testButton').data('target','#testModal2') you will not modify the data-target attribute but you will store the string "#testModal2" in "target" field. Then $('#testButton').data('target') will return "#testModal2".

确实可以使用.data('key')返回data-key属性值.但是您不能使用.data('key', 'newValue'进行设置.

It's true that .data('key') can be used to return the data-key attribute value. But you cannot set it using .data('key', 'newValue').

设置属性值最常见,最简单的方法是使用 .attr() 方法.

To set an attribute value the most common and easy way is to use .attr() method.

因此,答案很简单:在attr中更改data并使用data-target而不是target:

So, the answer is easy: change data in attr and use data-target instead of target:

$('#testButton').attr('data-target','#testModal2');

JSFIDDLE