开发者

Multi-line string insert using jQuery

$("#addSelect").click(function() {
        $("#optionsForm").after("Hel开发者_如何学Pythonlo world.");
} );

This works.

$("#addSelect").click(function() {
        $("#optionsForm").after("<tr>
    <td><input type="text" class="optionField" value="Options" /></td>
    <td>
        <ul class="option">
            <li><select><option>Value..</option></select></li>
        </ul>
    </td>
</tr>");
} );

Something like this doesn't.

In Chrome, I get the error "Unexpected token ILLEGAL". After Googling I've discovered my teeny brain doesn't know much about javascript and multi-lines. So I added '\' to then end of each line. Yet, I now get the error "Unexpected identifier".

I'd like this to not be as difficult as I'm making it :)


Change all the double quotes for the attributes to single quotes.

$("#addSelect").click(function() { 
        $("#optionsForm").after("<tr> \
    <td><input type='text' class='optionField' value='Options' /></td> \
    <td> \
        <ul class='option'> \
            <li><select><option>Value..</option></select></li> \
        </ul> \
    </td> \
</tr>"); 
} ); 


a cleaner approach is to use <script> tag

https://stackoverflow.com/a/12097933/1416458

<script id="stuff_you_want" type="text/plain">
<tr>
    <td><input type="text" class="optionField" value="Options" /></td>
    <td>
        <ul class="option">
            <li><select><option>Value..</option></select></li>
        </ul>
    </td>
</tr>
</script>

<script>

    // pure javascript
    var text = document.getElementById("stuff_you_want").innerHTML ;

    //or using jQuery... (document ready for safety)
    $(document).ready(function() {

        var text = $("#stuff_you_want").html(); 

    }

</script>

content-type must be set for html 4.0 compliance.


Use back ticks ` to start and finish the string

$("#addSelect").click(function() {
    $("#optionsForm").after(`<tr>
    <td><input type="text" class="optionField" value="Options" /></td>
    <td>
        <ul class="option">
            <li><select><option>Value..</option></select></li>
        </ul>
    </td>
</tr>`);
} );


I prefer to use something like this:

$('<tr bgcolor="#ffffe6"><td></td><td colspan="8" id="orderNotes">'
    + inputNotes.val() + '</td> <td>' + todayStamp
    + '</td> </tr>')

I feel like it's clean the + concatenation allows you to know we're working with the same black and it gives you the flexibility of adding variables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜