Easiest way to dyanmically load a DIV on button click?

半世苍凉 提交于 2019-12-08 12:52:43

问题


I have a relatively simple question here.

What I require is this; I need to have a page with 5 buttons at the top and a DIV beneath them (initially hidden). When a button is clicked, it loads content into the DIV (in the form of another DIV)
eg.

[Button 1] [Button 2] [Button 3] [Button 4] [Button 5] //5 buttons or links

<div id="content">
 // area for content to be loaded
</div>

<div id="content1">
//could be a table or image
</div>

<div id="content2">
//could be a table or image
</div>

<div id="content3">
//could be a table or image
</div>

<div id="content4">
//could be a table or image
</div>

<div id="content5">
//could be a table or image
</div>

In the above example, when the user loads the page they see 5 buttons. If they press button 5, it loads the "content5" DIV inside of the "content" DIV eg.

<div id="content">
 <div id="content5">
</div>
</div>

If another button is selected it loads it's content.

Can be achieved with jQuery or simple JavaScript.

Many thanks


回答1:


You need to bind a click handler on all of the buttons. Smart way in this particular example would be, to use the index of the elements to determine which div belongs to a button.

$('button').bind('click', function() {
    $('div#content').html($('div#content' + ($(this).index()+1)).html());
});

Demo: http://www.jsfiddle.net/8f8jt/

This will add an click event handler to all <button> nodes. On click, it looks for the index of the current clicked button (.index()help) and uses this value to query for the accordant <div> elements id. Once found, use .html()help to get and set the value.




回答2:


You also can use jQueryUI tabs, but it requires additional script.




回答3:


Try this

$('#button1').click(function() {
    $("#content").html(("#content1").html());
});

$('#button2').click(function() {
    $("#content").html(("#content2").html());
});

// etc

This way clears any existing content and copies the correct div into the main #content div.



来源:https://stackoverflow.com/questions/4883282/easiest-way-to-dyanmically-load-a-div-on-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!