2011-10-22 68 views
8
<div data-role="collapsible" data-content-theme="e" id="collapsePlace"> 
    <h3>Place:</h3> 
    <!--things...--> 
</div> 

如何在collapsible div中动态更改<h3>标题('Place:')的文本?Jquery Mobile:动态更改可折叠div的标题文本?

我想:

$('#collapsePlace').children('h3').text('new text'); 

而且它改变了文本 - 但失去所有的造型!

+0

我问了一个类似的问题,我认为我提供的答案是更好的: http://stackoverflow.com/questions/38978102/jquery-mobile-change-the-header-of-a-listview/38980002 #38980002 – ModusPwnens

回答

5

在jQuery Mobile的1.0RC2一个可折叠的实际HTML结构如下(框架取得了其通后的HTML):

<div id="collapsePlace" data-content-theme="e" data-role="collapsible" class="ui-collapsible ui-collapsible-collapsed"> 
    <h3 class="ui-collapsible-heading ui-collapsible-heading-collapsed"> 
     <a class="ui-collapsible-heading-toggle ui-btn ui-btn-icon-left ui-corner-top ui-corner-bottom ui-btn-up-c" href="#" data-theme="c"> 
      <span aria-hidden="true" class="ui-btn-inner ui-corner-top ui-corner-bottom"> 
       <span class="ui-btn-text">Place: 
        <span class="ui-collapsible-heading-status"> click to expand contents</span> 
       </span> 
       <span class="ui-icon ui-icon-plus ui-icon-shadow"></span> 
      </span> 
     </a> 
    </h3> 
    <div class="ui-collapsible-content ui-body-e ui-collapsible-content-collapsed" aria-hidden="true"> 
     <!--things...--> 
    </div> 
</div> 

<span class="ui-btn-text">元素内的嵌套<span>元件使这有点棘手。如果您想保留<span class="ui-btn-text">元素的结构,你将需要保存嵌套<span>元素,将其覆盖,然后替换:

//run code on document.ready 
$(function() { 
    var num = 1; 
    //add click handler to link to increment the collapsible's header each click 
    $('a').bind('click', function() { 
     //cache the `<span class="ui-btn-text">` element and its child 
     var $btn_text = $('#collapsePlace').find('.ui-btn-text'), 
      $btn_child = $btn_text.find('.ui-collapsible-heading-status'); 
     //overwrite the header text, then append its child to restore the previous structure 
     $btn_text.text('New String (' + num++ + ')').append($btn_child); 
    }); 
}); 

下面是上述解决方案的的jsfiddle:http://jsfiddle.net/jasper/4DAfn/2/

+0

完美的作品,非常感谢! – Matthieu

0

一个容易的选择是给H3自定义的ID /类,例如:

<div data-role="collapsible" data-content-theme="e" id="collapsePlace"> 
    <h3 id='h3Text'>Place:</h3> 
    <!--things...--> 
</div> 

这样,你只需要做到:

$('#collapsePlace #h3Text').text('new text'); 
+0

我不知道它是否适用于以前版本的JQM,但它不适用于1.2.0 –

+0

,正如您可以在此小提琴中看到的那样,虽然文字发生更改,但样式会被删除。 http://jsfiddle.net/AQZQs/ –

+0

1.2为我工作 – akiva

2

简单的解决办法是

$('#collapsePlace .ui-btn-text').text("hello "); 

http://jsfiddle.net/AQZQs/1/

+1

这将从问题HTML中显示的'.ui-btn-text'元素中移除HTML。 – Jasper

+0

用于以后的jQuery移动版本(用v 1.4.3测试),用“.ui-collapsible-heading-toggle”替换“.ui-btn-text” –

4

在1.3.2,下面的检查了小提琴似乎工作:

<div id="MyID" data-role="collapsible" >  
    <h3><span id="MyHeaderID">My Header</span></h3>  
    <!-- My Content --> 
</div> 

JQuery的:

$("#MyID h3 #MyHeaderID").text("Your New Header"); 

快乐编码!

+0

正在寻找这个。大! – user3023313

相关问题