Mohammad Masoumi
Mohammad Masoumi

Reputation: 11

Nested quotes in javascript and html

I have a big problem with quotes in java script and html dom. I want to use just double quotes("), not ' at all! Here is my code:

<a onclick="aClicked("<span onclick="spanClicked("You clicked me")">I'm an Span</span>")">Add span</a>

<script type="text/javascript">
function aClicked(str) {
    $(document).append(str);
}
function spanClicked(str) {
    alert(str);
}
</script>

Can anyone help throw kind of these problems!? Tanks.

here is my original code (it work correctly but I just want to simplfy it and underestand it): "I call this function with ajax"

<?php
function getTags() {
        $values = ['test1', 'test2'];
        $valuesString = '';
        $baseSpanString = '<span><span class="tag">?</span><a onclick="Tags.Update($(this).parent().parent(), $(this).parent(), &quot;tag&quot;);">x</a></span>';
        foreach ($values as $tmpValue) {
            if(trim($tmpValue) == '') {
                continue;
            }
            $valuesString .= str_replace('?', $tmpValue, $baseSpanString);
        }

        $xhtml = '
                <div>
                    <input type="text" onkeydown="return Tags.Insert($(this).parent(), $(this), event, \''.str_replace('"', '\\\'', $baseSpanString).'\', \'tag\');"/>
                    <textarea style="display:none;">'.implode('-', $values).'</textarea>
                    '.$valuesString.'
                </div>
        ';

        return $xhtml;  
}
?>  

<script type="text/javascript">

Tags = {};
Tags.Update = function(div, span, tagClass) {
    div = $(div);
    if(!div.length) {
        alert('Error');
        return false;
    }
    $(span).remove();
    var tagsSpan = $('.'+tagClass, div);
    var tagsString = [];
    if(tagsSpan.length) {
        $.each(tagsSpan, function(index, val) {
            tagsString.push($(val).text());
        });
    }
    $('textarea', div).text(tagsString.join('-'));
};
Tags.Insert = function(div, input, event, baseSpanString, tagClass) {
    if (event.keyCode == 13)
    {
        div = $(div);
        input = $(input);
        if(!div.length || !input.length) {
            alert('Error');
            return false;
        }
        var val = input.val();
        if(val && val != '') {
            input.val('');
            var spanString = baseSpanString.replace('?', val);
            div.append(spanString);
        }
        var tagsSpan = $('.'+tagClass, div);
        var tagsString = [];
        if(tagsSpan.length) {
            $.each(tagsSpan, function(index, val) {
                tagsString.push($(val).text());
            });
        }
        $('textarea', div).text(tagsString.join('-'));
        return false;
    }
};

</script>  

Upvotes: 0

Views: 2111

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

Two answers:

  • Your string question
  • The right way instead

Your string question

' is the feature specifically designed for this. But sometimes this stuff does legitimately come up...

The key is to be aware of what kind of text you're dealing with at each stage:

  • Within the " of the attribute (onclick="..."), you're writing HTML text, even though what you're writing in that HTML text is JavaScript. So you can use &quot; for quotes if you insist on not using '.

  • If you need to use a string within your JavaScript code (such as the onclick in the string we're passing aClicked) and insist on not using ', put a \ before the &quot;.

  • If you need to use a quote within an HTML string within an HTML string (such as the string being passed to spanClicked, which is an HTML string inside a JavaScript string inside an HTML string), then you need something that will end up being &quot; after the entities in the first HTML string are processed. So that's &amp;quot;

So:

<a onclick="aClicked(&quot;<span onclick=\&quot;spanClicked(&amp;quot;You clicked me&amp;quot;)\&quot;>I'm an Span</span>&quot;)">Add span</a>

Example:

function aClicked(str) {
    $(document.body).append(str);
}
function spanClicked(str) {
    alert(str);
}
<a onclick="aClicked(&quot;<span onclick=\&quot;spanClicked(&amp;quot;You clicked me&amp;quot;)\&quot;>I'm an Span</span>&quot;)">Add span</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The right way instead

But again, this is all just a way to make your code complicated unmaintainable; instead, just use jQuery, as you're already using jQuery:

Example:

$("a").on("click", function() {
    var span = $("<span>I'm a span</span>");
    span.on("click", function() {
      spanClicked("You clicked me");
    });
    $(document.body).append(span);
});
function spanClicked(str) {
    alert(str);
}
<a>Add span</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Sagar V
Sagar V

Reputation: 12478

Better make it as a function like this

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onclick="adds();">Add span</a>

<script type="text/javascript">
function adds(){
  aClicked("<span onclick='spanClicked(\"You clicked me\")'>I'm an Span</span>");
}
function aClicked(str) {
    
    $(document.body).append(str);
}
function spanClicked(str) {
    alert(str);
}
</script>

Upvotes: 0

Satpal
Satpal

Reputation: 133403

As you are using jQuery use unobtrusive event handlers, for this .on() method can be used. When generating elements dynamically you need to use Event Delegation.

I would also recommend you to use semantically correct elements, thus used <button> element

$("#addSpan").on("click", function() {
  $('#container').append("<span class=\"myspan\">I'm an Span</span><br/>");
})

$("#container").on("click", ".myspan", function() {
  console.log("You clicked me");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="addSpan">Add span</button>
<div id="container">
</div>

Upvotes: 1

Related Questions