简体   繁体   中英

How can i change dynamically the content tab of jquery ui accordion

I have the next code:

<div id="accordion">
    <h3>Row 1</h3>
    <div id="1"></div>
    <h3>Row 2</h3>
    <div id="2"></div>
    <h3>Row 3</h3>
    <div id="3"></div>
</div>

$("#accordion").accordion({
    autoHeight: false,
    clearStyle: true,
    active: 0,
    change: function(event, ui) {
    $("div#2").append('<p>Test</p>');
    }
});

When the accordion is clicked in another row, i want to fill the <div id="2"> with data. On change event i am trying this:

$("div #2").append('<p>Test</p>');

But the text "Test" is printed inside the h3 instead the div... how can i achieve to print the text on the div???

I am using jquery 1.9.0

It seems like a bug http://bugs.jqueryui.com/ticket/4469#comment:4 isnt it?

You'll have to redo the values you set for the id attributes. Try:

<div id="accordion">
    <h3 id="header1">Row 1</h3>
    <div id="content1"></div>
    <h3 id="header2">Row 2</h3>
    <div id="content2"></div>
    <h3 id="header3">Row 3</h3>
    <div id="content3"></div>
</div>

That way, you can easily target which:

$("#content2").append('<p>Test</p>');

(or actually use .append() )

This is because the id attribute must be unique in order to target the element you actually want. jQuery will use the native document.getElementById method that will return the first found element with that id .

UPDATE:

Per your new edit, you need to use the selector without a space:

$("div#2").append('<p>Test</p>');

Although you do not need to include the div part of the selector. Just use:

$("#2").append('<p>Test</p>');

While HTML5 does allow the id to start with a number (and be 1 character long), I would suggest using a more descriptive id , like before I said: "content1", etc.

UPDATE 2:

Looking it over again, the $("div #2") should actually work as well, since the element with the id "2" is in a <div> . So technically that selector should work. Nonetheless, I'd still suggest a selector that isn't a number and is more descriptive.

With your code, I got it working with a more descriptive selector anyways: http://jsfiddle.net/BrRPz/2/

In css, id selector is unique element. so don't repeat a same id in the page

<div id="accordion">
    <h3 id="1">Row 1</h3>
    <div class="1"></div>
    <h3 id="2">Row 2</h3>
    <div class="2"></div>
    <h3 id="3">Row 3</h3>
    <div class="3"></div>
</div>

use script as

$("div.2").append('<p>Test</p>');

Note: id selector is unique element.

Try $("div#2").append('<p>Test</p>');

$("div #2") will target an element with id='2' inside of a <div> element, whereas $("div#2") targets a <div> with id='2' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM