Вопрос

How would I create a list of the user's inputs using createElement()? Something so that when somebody adds text into the prompt("enter text") box, it displays on the screen. I've tried researching createElement(), but I'm still only able to display the latest input using a variable.

Edit:

<script>

function myFunction()
{
var user =prompt("Enter your name:")
var text =prompt("Hello " + user + ". Enter some text:")
count++;
document.getElementById("count").innerHTML=count;
document.getElementById("latest").innerHTML=text;
}

</script>

<p>Total: <span id="count">0</span></p>
<p>Latest blocked term: <span id="latest"></span></p>
<button onclick="myFunction()">Click</button>

I've cut off unrelated parts, so I hope this works.

Это было полезно?

Решение 2

You have two options here.

The DOM way

This is the way that you are searching for with createElement. It is the best way in a sense, because it allows you to interact with the DOM as it already exists. You don't however need createElement: you should really use createTextNode, which does what it says on the tin:

function myFunction() {
    var name = prompt("Enter some text:"),
        node = document.createTextNode(name);
    document.getElementById('latest').appendChild(node);
}

jsFiddle example

(This results in adding the text to the end of the element: it does not remove the content that is already there.)

The realistic way

While using the DOM functions is all well and good, it is not really idiomatic Javascript. In reality, innerHTML is the property you should probably be using. Browsers are really good at parsing HTML (it's what they're built for, after all!) so this will almost certainly be quicker than the DOM method.

function myFunction() {
    var name = prompt("Enter some text:");
    document.getElementById('latest').innerHTML = name; // to overwrite the existing contents
    document.getElementById('latest').innerHTML += name; // to add to the existing contents
}

jsFiddle example

There are other ways, such as using createDocumentFragment, but this second method is almost certainly the way for you to go.

Другие советы

You need to create input box every time user enter text in prompt

function addInput(){
    var text = prompt("");
    var input = document.createElement('input');
    input.value = text;
    document.body.appendChild(input);

}

The super short way:

function renderInput(){
    document.getElementById("latest").innerHTML += prompt("What is your name?") + "<br />";
}

Using your example:

<script>
    function myFunction() {
        document.getElementById("latest").innerHTML += prompt("Enter some text:") + "<br />";
    }
</script>

<p>Latest text: <span id="latest"></span></p>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top