使用jQuery多次添加和删除元素

时间:2011-09-29 20:18:52

标签: javascript jquery html

我在点击按钮时使用jQuery附加YouTube视频。

onclick="$('#videogallery').append('<iframe width=725 height=398 src=http://www.youtube.com/embed/8Pi-dHJSkrk frameborder=0 allowfullscreen></iframe>');"

然后我再次使用jQuery在单击另一个按钮时将其删除。

onclick="$('iframe').remove();"

第一次工作正常,但如果我添加视频,请将其删除,然后尝试再次添加。它会立即添加和删除。

为什么会这样?似乎 $('iframe')。remove(); 函数在单击按钮后不断运行。

编辑

以下是代码的扩展版本。

   <div class="product-media" id="product-media1">
    <map name="submenu3" onclick="$('iframe').remove();">
      <area shape="rect" coords="0, 0, 95, 25"  onClick="swap3('product-media1','product-details1');">
      <area shape="rect" coords="103, 0, 213, 25"  onClick="swap3('product-media1','product-specs1');">
    </map>
    <img src="images/submenu3.jpg" alt="" border="0" usemap="submenu3" /><br /><br />
    <p>&nbsp;</p>
    <div id="videogallery">
                <a rel="#voverlay" href="#" onclick="$('#videogallery').append('<iframe width=725 height=398 src=http://www.youtube.com/embed/8Pi-dHJSkrk frameborder=0 allowfullscreen></iframe>');">
        <span class="thumb" onClick="swapvid"><img src="images/video.jpg" alt="" align="left" /></span><span></span>
      </a><br />
      &nbsp;&nbsp;Watch Scotch-Brite&trade; Radial Discs in action
    </div>
  </div>

1 个答案:

答案 0 :(得分:4)

这很好用:http://jsfiddle.net/YssHJ/

$('#add').click(function(){
    $('#vid').append('<iframe width=725 height=398 src=http://www.youtube.com/embed/8Pi-dHJSkrk frameborder=0 allowfullscreen></iframe>');

});


$('#del').click(function(){
    $('iframe').remove();
});

编辑:使用地图click http://jsfiddle.net/YssHJ/2/

小提琴