使用Jquery或JS添加和删除div

时间:2014-04-29 16:28:53

标签: javascript jquery html css

我正在制作一个预先加载了视频背景的网站,因此我的所有内容都需要位于同一页面上。我有一个div,我的第一部分就像“slide1”一样。我需要删除此div并在按钮单击时将其替换为“slide2”。我已经尝试使用javascript在点击上加载“slide2”的html但我尝试的代码只是将div写入没有样式的白页。我需要将它加载到我的内容div中,并使用适当的样式。

我的HTML代码:

<script src="assets/js/introduction.js"></script>

</head>

<body>

<div id="container">

<div id="content">


    <div id="slide1">
    <p>Here is the first trigger. It should look something like this</p>
    <p><input type="button" onclick="part2()" value="Click Me!" /></p>
    </div>



</div>

包含内容的javascript文件:

function part2() {
    document.write('\
      <div id="slide2">\
        <p>Here is the second trigger. It should be to the left</p>\
        <p>next line goes here</p>\
      </div>'
    );
}

我已经被困在这几天了,这让我疯了。任何帮助都会很棒

4 个答案:

答案 0 :(得分:1)

为什么不在html中创建所有幻灯片并隐藏除幻灯片1以外的所有幻灯片? 然后,当他们点击按钮隐藏幻灯片1并显示幻灯片2.像这样的东西

<div id="content">
 <div class="slide">Slide 1</div>
 <div class="slide">Slide 2</div>
 <div class="slide">Slide 3</div>
 <div class="slide">Slide 4</div>
</div>
<a href="#" id="next-button">Next</a>

JS

$(function(){
  var currentSlide = 0;
  $(".slide").hide();
  $(".slide:eq(0)").show();
  $("#next-button").on("click",function(e){
    e.preventDefault();
    $(".slide:eq(" + currentSlide + ")").hide();
    if(currentSlide == $(".slide").length - 1){
      currentSlide = 0;   
    }else{
        currentSlide++;
    }
    $(".slide:eq("+ currentSlide +")").show();
  });
  });

http://jsfiddle.net/cNTgQ/1/

答案 1 :(得分:0)

如果您对JQuery没问题,请尝试使用.replaceWith()

有关详细信息,请参阅official页面。

答案 2 :(得分:0)

你可以用这个:

    function part2() {

    var html = '<div id="slide2"><p>Here is the second trigger. It should be to the left</p><p>next line goes here</p></div>';
//here you append the slide2;
    $('#content').append(html);
//here you remove it
    $('#slide1').remove();
    }

答案 3 :(得分:0)

就像其他人说的那样,尝试使用jQuery中的replaceWith(),这是你的功能:

 function part2() {
        var content = '<div id="slide2"><p>Here is the second trigger. It should be to the left</p><p>next line goes here</p></div>';
        $('#slide1').hide().replaceWith(content).show();
    }
相关问题