Вопрос

I am pretty new to Javascript and this is the first time I have come across this type of concatenation while taking a JQuery course. My question is regarding the + sign and why it is needed with all the quotes before the ">" to close the HTML tag. In other words the + "'> " part of the code. Why can't you just end the quotes and close the tag without a plus sign? Can someone break that down step by step? I left a comment in the script where I am confused. There are 2 instances. Thanks.

<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() { //This is the part 
            $(this).html("<a name='bookmark" + cAnchorCount + "'></a>" + $(this).html());       
            oList.append($("<li><a href='#bookmark" + cAnchorCount++ + "'> " + $(this).text() + "</a></li>"));
        });

        $("#" + sBookMarkNode).append(oList);
    }
</script>
Это было полезно?

Решение

You already ended the string literal, back here:

"<li><a href='#bookmark"
//                     ^ here

Now you’re concatenating an expression to the string before it, and concatenating the result of that concatenation with another string literal, and concatenation is done with the + operator.

If we replace the literals with placeholders representing expressions (which they are), and add parentheses, it might become clearer:

oList.append($(A + (cAnchorCount++) + B + ($(this).text()) + C));

Note that the HTML here isn’t special in any way; the strings you have here are strings like any other. They just happen to represent HTML. (I’d recommend learning the W3C DOM before jQuery, by the way; it makes this separation clearer.)

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

The script is building an HTML element in Javascript by concatenating strings together. You can think of it this way:

tag_opening + anchor_count + tag_closing

The + is necessary because it’s adding strings together. Without it, you would just be following one string with another, which would result in a syntax error.

The plus here is used for concatenation. What you're really doing is adding a string which you've written (a name='bookmark) plus a variable (cAnchorCount), plus another string ('>) to make one long string. Without the plus, the syntax makes no sense.

Your example is unclear, but you are combining a variable an an HTML string:

"<a href='#bookmark" + cAnchorCount++ + "'> "  

Will evaluate to something like:

<a href='#bookmark1'>

The code you listed uses external double quote (") to wrap the string and internal single quotes (') to wrap the attribute values. There is no interpolation in JavaScript strings, only string concatenation.

They are trying to format a string so that once the code compiles, it will be readable HTML.

For example:

oList.append($("<li><a href='#bookmark" + cAnchorCount++ + "'> " + $(this).text() + "</a></li>")); is trying to ultimately get

<li><a href='#bookmark3'>TEXT</a></li>

You need the '> to close the tag properly from <a href=' after adding in text.

In this case it has nothing to do with HTML or the content of the strings being concatenated, it's just that JavaScript uses the + operator to concatenate strings. I imagine every language uses some operator to do this. For example:

var result = 'first string' + 'second string';

This creates the concatenated string:

'first stringsecond string'

Now if one of those strings happens to be a variable, the same thing happens:

var someVariable = 'second string';
var result = 'first string' + someVariable;

This still results in the same concatenated string:

'first stringsecond string'

That's all the code in the question is doing in these cases. Concatenating one string to another. For example:

$("div:not([id=header]) " + strWhichTag)

The variable strWhichTag contains some string value, likely the name of an HTML tag judging by its name and usage. So if it contains something like 'div' then the result is:

$("div:not([id=header]) div")

This overall resulting string is then being evaluated by jQuery as a selector to identify a set of HTML elements on which to operate. But the string concatenation doesn't matter, it could just as easily result in this:

$("div:not([id=header]) some nonsense")

if the strWhichTag variable contained the value 'some nonsense'.

THis is called concatenation, the # which is the ID of the string, while the sBookMarkNode is the variable. Then when the page loads it will append (create) right after the # + sBookMarkNode which the variable sBookMarkNode is created apparently else where or is a global variable since I cannot see it in your code snippet.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top