简体   繁体   English

如何将外部HTML添加到div

[英]How to add external html into a div

i have a HTML file index.HTML. 我有一个HTML文件index.HTML。 i wanna load external files( 1.HTML, 2.HTML, 3.HTML) into a div on button click my HTML is something like this 我想将外部文件(1.HTML,2.HTML,3.HTML)加载到div上,单击按钮,我的HTML就是这样

<div class="buttons">
<button  type="button">button1</button>
<button  type="button">button2</button>
<button  type="button">button3</button>
</div>

<div class="mydiv">

</div>

on click of button1 1.HTML content to be loaded in above div. 在button1上单击1. HTML内容将在以上div中加载。 on click of button2, 2.HTML.. and etc. 单击button2、2.HTML等。

i am very new to java script so let me know how to write a script for this. 我是Java脚本的新手,所以让我知道如何为此编写脚本。 Any help would be appreciated. 任何帮助,将不胜感激。 thanks in advance 提前致谢

use load() .. and data attirbutes .. try this 使用load() ..和数据属性..试试这个

html html

<div class="buttons">
<button  type="button" data-url="1.html">button1</button>
<button  type="button" data-url="2.html">button2</button>
<button  type="button" data-url="3.html">button3</button>
</div>

jquery jQuery的

$("button").click(function(){
    $('.mydiv').load($(this).data('url'));
});

NOTE: the selector $('button') selects all the button present in the document.. so its better you give them a class and select it to be specific using class selector . 注意:选择器$('button')选择文档中存在的所有按钮..因此,最好给他们一个类,然后使用类选择器进行选择.

to be more specific 更加具体

$('.buttons > button').click(function(){
     $('.mydiv').load($(this).data('url'));
});

OR 要么

<div class="buttons">
<button  type="button" data-url="1.html" class="btnclass">button1</button>
<button  type="button" data-url="2.html" class="btnclass">button2</button>
<button  type="button" data-url="3.html" class="btnclass">button3</button>
</div>

$(".btnclass").click(function(){
    $('.mydiv').load($(this).data('url'));
});

您可能需要使用jQuery load()

$('#mydiv').load('test.html');

您只需要在后面附加html

$('#').append('html content')

try this 尝试这个

 $(document).ready(function(){
    $("button").click(function(){
  var file = $(this).attr('number')+'.html';
  $('.mydiv').load(file);
  })
})
<div class="buttons">
<button  number= '1'  type="button">button1</button>
<button  number= '2'  type="button">button2</button>
<button  number= '3'  type="button" >button3</button>
</div>

<div class="mydiv">

</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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