如何更新现有的Bootstrap模态数据目标? [英] How do you update an existing Bootstrap modal data-target?

查看:90
本文介绍了如何更新现有的Bootstrap模态数据目标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用jquery .datadata-target="#testModal1"更新现有的data-target以指向#testModal2模态,但是即使在data属性更改后,它仍然仍链接到#testModal1

I tried to update an existing data-target with a data-target="#testModal1" to point to the #testModal2 modal using jquery .data, but even after the data attribute change it still is linked to #testModal1

//Jquery:

$('#testButton').data('target', '#testModal2')

<!-- HTML: -->


<button id='testButton' data-toggle="modal" data-target="#testModal1">
      Test
    </button>

<div class="modal fade" id="testModal1" tabindex="-1" role="dialog" aria-hidden="true" style='display:none'>
  <div class="modal-dialog">
    <div class="modal-content">
      Testing Testing 1
    </div>
  </div>
</div>

<div class="modal fade" id="testModal2" tabindex="-1" role="dialog" aria-hidden="true" style='display:none;'>
  <div class="modal-dialog">
    <div class="modal-content">
      Testing Testing 2
    </div>
  </div>
</div>

推荐答案

让我们看看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

这篇关于如何更新现有的Bootstrap模态数据目标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆