繁体   English   中英

如何将外部HTML添加到div

[英]How to add external html into a div

我有一个HTML文件index.HTML。 我想将外部文件(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>

在button1上单击1. HTML内容将在以上div中加载。 单击button2、2.HTML等。

我是Java脚本的新手,所以让我知道如何为此编写脚本。 任何帮助,将不胜感激。 提前致谢

使用load() ..和数据属性..试试这个

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的

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

注意:选择器$('button')选择文档中存在的所有按钮..因此,最好给他们一个类,然后使用类选择器进行选择.

更加具体

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

要么

<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')

尝试这个

 $(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