admin管理员组

文章数量:1431763

I found the following code snippet and am looking for some clarification on how it works, because it solves what I'm hoping to do. The variable 'html' is a string, which is returned form the function showCard, and is placed into the HTML code as a div. I'm able to replicate this however the string output is returned and starts with: "..." so the div isn't created, the string is simply moved into my HTML because the quotes remain outside the div.

function Card(suit, val, name, symbol)
{
        this.suit = suit;
        this.val = val;
        this.name = name;
        this.symbol = symbol;

    this.showCard =function showCard()
    {
        var html="";
        switch(this.suit)
        {
            case "hearts": suit_text = "♥";
            break;
            case "diamonds": suit_text = "♦";
            break;
            case "spades": suit_text = "♠";
            break;
            case "clubs": suit_text = "♣";
            break;
        }
        html="<div class='card " + this.suit + "'><div class='card-value'>" + this.symbol + "</div><div class='suit'>" + suit_text + "</div><div class='main-number'>"+this.symbol +"</div><div class='invert card-value'>"+this.symbol+"</div><div class='invert suit'>"+suit_text+"</div></div>";
        return html;
    }
}

I found the following code snippet and am looking for some clarification on how it works, because it solves what I'm hoping to do. The variable 'html' is a string, which is returned form the function showCard, and is placed into the HTML code as a div. I'm able to replicate this however the string output is returned and starts with: "..." so the div isn't created, the string is simply moved into my HTML because the quotes remain outside the div.

function Card(suit, val, name, symbol)
{
        this.suit = suit;
        this.val = val;
        this.name = name;
        this.symbol = symbol;

    this.showCard =function showCard()
    {
        var html="";
        switch(this.suit)
        {
            case "hearts": suit_text = "&hearts;";
            break;
            case "diamonds": suit_text = "&diams;";
            break;
            case "spades": suit_text = "&spades;";
            break;
            case "clubs": suit_text = "&clubs;";
            break;
        }
        html="<div class='card " + this.suit + "'><div class='card-value'>" + this.symbol + "</div><div class='suit'>" + suit_text + "</div><div class='main-number'>"+this.symbol +"</div><div class='invert card-value'>"+this.symbol+"</div><div class='invert suit'>"+suit_text+"</div></div>";
        return html;
    }
}
Share Improve this question asked Nov 14, 2015 at 15:42 KM617KM617 1351 gold badge4 silver badges17 bronze badges 11
  • 2 switch is similar to a series of ifs. Please be warned, suit_text is not being vard anywhere in the code you've shared here – Paul S. Commented Nov 14, 2015 at 15:45
  • What part of this code do you not understand? – jfriend00 Commented Nov 14, 2015 at 15:48
  • 1 It looks like it's being put into the DOM for me: jsfiddle/bz72wkrj How are you actually inserting the elements? – arcyqwerty Commented Nov 14, 2015 at 15:49
  • var html=""; just initialises the variable to the empty string. It could be rewritten to jsfiddle/6ja9sjL2/1 if you do not like the var html... The suit_test is now a global var the way it is used – mplungjan Commented Nov 14, 2015 at 15:49
  • How do you call this function? Make sure to properly create a Card instance with new Card(....), and to declare the variable suit_text. – trincot Commented Nov 14, 2015 at 15:53
 |  Show 6 more ments

3 Answers 3

Reset to default 0

If you use createTextNode, your HTML will be treated as regular text. Easiest way is to update the innerHTML of a node.

function Card(suit, val, name, symbol)
{
        this.suit = suit;
        this.val = val;
        this.name = name;
        this.symbol = symbol;

    this.showCard =function showCard()
    {
        var html="";
        switch(this.suit)
        {
            case "hearts": suit_text = "&hearts;";
            break;
            case "diamonds": suit_text = "&diams;";
            break;
            case "spades": suit_text = "&spades;";
            break;
            case "clubs": suit_text = "&clubs;";
            break;
        }
        html="<div class='card " + this.suit + "'><div class='card-value'>" + this.symbol + "</div><div class='suit'>" + suit_text + "</div><div class='main-number'>"+this.symbol +"</div><div class='invert card-value'>"+this.symbol+"</div><div class='invert suit'>"+suit_text+"</div></div>";
        return html;
    }
}

var card = new Card('hearts', 1, 'Hearts', 'heart-symbol');
var container = document.createElement('div');
container.innerHTML = card.showCard();
// We could insert the container div, but we don't really need it.
document.querySelector('div').appendChild(container.firstChild);
<div>
  Insert content here
</div>

Here are a couple examples of how you might convert a HTML String to DOM

  1. If you're expecting the HTML String to start with any content which is valid inside a <div>

    function str2dom(str) {
        var d = document.createElement('div'),
            df = document.createDocumentFragment();
        d.innerHTML = str;
        while (d.childNodes.length)
            df.appendChild(d.childNodes[0]);
        return df;
    }
    
  2. If you're expecting the HTML String to start with <doctype>, <html>

    function html2dom(str) {
        return (new DOMParser).parseFromString(str, 'text/html');
    }
    

If you're starting with <body> you may need to modify one of the above methods.
If your HTML is invalid you may get an Error


After using one of the above methods, you can append what you want to a node of your choice with parent.appendChild(node_to_be_appended);


If you're asking how to create a Node instead of a String, use the DOM methods, such as document.createElement

function makeNode(tag, attribs, text) {
    var e = document.createElement(tag),
        k;
    if (attribs)
        for (k in attribs)
            e.setAttribute(k, attribs[k]);
    if (text)
        e.textContent = text;
    return e;
}

makeNode('span');
// HTMLSpanElement <span></span>​

makeNode('span', {class: 'foo', id: 'bar'});
// HTMLSpanElement <span class=​"foo" id=​"bar">​</span>​

makeNode('span', {class: 'foo', id: 'bar'}, 'hello world');
// HTMLSpanElement <span class=​"foo" id=​"bar">hello world​</span>​

You could create the outer div using document.createElement and then populate the rest of the HTML using its innerHTML property.

function Card(suit, val, name, symbol)
{
        this.suit = suit;
        this.val = val;
        this.name = name;
        this.symbol = symbol;

    this.showCard =function showCard()
    {
        var html="";
        switch(this.suit)
        {
            case "hearts": suit_text = "&hearts;";
            break;
            case "diamonds": suit_text = "&diams;";
            break;
            case "spades": suit_text = "&spades;";
            break;
            case "clubs": suit_text = "&clubs;";
            break;
        }
        html="<div class='card-value'>" + this.symbol + "</div><div class='suit'>" + suit_text + "</div><div class='main-number'>"+this.symbol +"</div><div class='invert card-value'>"+this.symbol+"</div><div class='invert suit'>"+suit_text+"</div>";

        var div = document.createElement('div');
        div.classList.add('card');
        div.classList.add(this.suit);
        div.innerHTML = html;
        return div;
    }
}

The returned div can then be passed directly to document.body.appendChild like so:

document.body.appendChild(new Card(...).showCard());

Note that using innerHTML can, in some cases, lead to security issues if you're not careful with the inputs. Make sure that the arguments you use to create cards are sanitized if ing from the user!

As an additional note, you might want to consider including the append operation in showCard or changing the name of showCard to something that is more descriptive of what it actually does (i.e. createCard)

本文标签: javascript function return text to htmlStack Overflow