문제

I have been researching a clean way to add a DIV to a page and add a line of text dynamically. However most of the stuff I come across deals with existing DIVs in the page already and not exactly creating a new one.

I am not super familiar with JQuery but I am getting there and tried this code but for some reason not getting the desired result, can someone please tell me what I am doing wrong?

var theResponse = prompt('Which Group?');
//alert(theResponse);
var groupDiv = $('#groupDiv');
$('body').append(groupDiv);
$('#groupDiv').css({"marginLeft":"10px", "marginTop":"10px"});
$('#groupDiv').append("Group: "+theResponse);
$('#groupDiv').show();
switch (theResponse) 
{
    case "1":
    //alert("case 1");
        break;
    case "2":
    //alert("case 2");
        break;
    case "3":
    //alert("case 3");
        break;
    default:
    //alert("default");
        //
}

I am hoping its not some dumb rookie mistake but any help is appreciated. I am running it using GreaseMonkey and TamperMonkey with all of the code working fine (meaning everything besides that first DIV creation).

도움이 되었습니까?

해결책

I think this answers your question:

var theResponse = prompt('Which Group?');
$('body').append('<div id="groupDiv"></div>');
$("#groupDiv").css({"marginLeft":"10px", "marginTop":"10px"});
$('#groupDiv').text("Group: " + theResponse);

Fiddle

다른 팁

When you do this:

var groupDiv = $('#groupDiv');

You get an existing element with id groupDiv. If you append it somewhere, you remove it from the previous place. If you want to clone it (duplicate), use:

var groupDiv = $('#groupDiv').clone();

If you want to create something from scratch, use:

var groupDiv = $('<div class="groupDiv"></div>');

You can also add all parameters in one go:

var groupDiv = 
    $('<div class="groupDiv" style="marginLeft:10px, marginTop:10px">Group: ' +
    theResponse + '</div>');

And then add to the body as you did:

$('body').append(groupDiv);

You don't need to show() if it wasn't hidden, or if it didn't had display:none style.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top