문제

I'm trying to make two buttons that acts as remove and add function first I have this:

HTML

<video id="localVideo" style="background-color:black"></video>
<div id="remoteVideos"></div>

Buttons

<button id="BtnOn">On</button>
<button id="BtnOff">Off</button> 

Script:

$(document).ready(function() {

            //$("#BtnOn").click(function() {
             //   $('#A').append("<div id='localVideo'>");
             //   $('#A').append("<div id='remoteVideos'>");            
        //});

            $("#BtnOff").click(function() {
                $("#localVideo").remove();
        $("#remoteVideos").remove();
        });    
            });

What I'm trying to do is remove the 2 div's and have the ability to return them, with the condition that you can only add them if they are missing and remove them if they are present, therefore limiting them to 1 add and 1 remove. How can I accomplish this?Any help suggestion is appreciated

도움이 되었습니까?

해결책

You could check if the #localVideo element exists. Also, if they are the only elements in the #A element, you can remove them by calling $('#A').empty();.

$(document).ready(function() {
    $('#BtnOn').click(function() {
        if ($('#localVideo').length == 0) {
            $('#A').append('<video id="localVideo" style="background-color:black"></video><div id="remoteVideos"></div>');
        }
    });

    $('#BtnOff').click(function() {
        if ($('#localVideo').length > 0) {
            $("#localVideo").remove();
            $("#remoteVideos").remove();
        }
    });    
});

You could also consider hiding and showing the video elements, rather than adding and removing them.

다른 팁

Instead of using .append() and .remove(), you can change the CSS display property to none or initial, depending on whether you want the thing to be shown or not.

This way, you can then add an if statement like so:

$("#BtnOff").click(function() {
    if('#localvideo').css('display') == 'none'){
        //do nothing
    } else {
        $('#localVideo').css('display','none');
        $('#remoteVideos').css('display','none');
    }
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top