Question

I am new to javascript and was hoping someone might be able to explain to me why certain quotes are placed where they are. I understand in the code below, where I left comments, that it is 3 strings being combined into one however I do not understand why the quotes are placed where they are. I'm sure the answer is obvious but I am having trouble wrapping my head around it. As I under stand it the 3 parts are tag_opening + anchor_count + tag_closing. Just confused on the single ' ' quotes and why they are where they are. Thank you in advance.

<script type="text/javascript">

    $("document").ready(function() {    
        buildBookmarks('h3', 'header'); 
    }); 

    function buildBookmarks(strWhichTag, sBookMarkNode) {

        var cAnchorCount = 0;
        var oList = $("<ul id='bookmarksList'>");

        $("div:not([id=header])" + strWhichTag).each(function() {
            //I'm confused on the quotation placement and why it cannot look like this: 
            //"<li><a href='#bookmark" + cAnchorCount++' + ">" -OR- 
            //"<a name='bookmark" + cAnchorCount + >' + "</a>"
            $(this).html("<a name='bookmark" + cAnchorCount + "'></a>" + $(this).html());
            oList.append($("<li><a href='#bookmark" + cAnchorCount++ + "'>" + $(this).text() + "</a></li>"));
        });
        $("#" + sBookMarkNode).append(oList);
    }
</script>
Était-ce utile?

La solution

This is because to create valid markup, the attribute values need to be wrapped, be it in single quotes or double quotes. Fortunately, the use of which type doesn't matter, as long as you're consistent within a given string (though at least try to use the same approach in all your code).

As an example, this line:

$("<li><a href='#bookmark" + cAnchorCount++ + "'>" + $(this).text() + "</a></li>")

Would generate this markup:

<li><a href='#bookmarkSomeAnchorCount'>Some Text</a></li>

And the same would be true if you reverse the use of quotes. This new line:

$('<li><a href="#bookmark' + cAnchorCount++ + '">' + $(this).text() + '</a></li>')

Would generate this markup:

<li><a href="#bookmarkSomeAnchorCount">Some Text</a></li>

In essence, one quote type is being used to delineate string literals while the other is a character you want to include within the resulting string because the resulting markup requires it to be valid.

Autres conseils

The answer is quite simple. " and ' are exactly the same in JavaScript and you can have a string with one of them, if its quoted with the other.

Generally HTML properties use ". So to have a template HMTL string with a lot of ", its easier to quote the JavaScript string with '.

For this reason, I have seen JS projects use ' alone consistently.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top