javascript
  • jquery
  • 2014-01-18 63 views 10 likes 
    10

    我如何在多行像jQuery聲明一個變量的字符串變種,聲明與多條線路在JavaScript/jQuery的

    原始變量:

    var h = '<label>Hello World, Welcome to the hotel</label><input type="button" value="Visit Hotel"><input type="button" value="Exit">'; 
    

    我要聲明的變量:

    var h = '<label>Hello World, Welcome to the hotel</label> 
           <input type="button" value="Visit Hotel"> 
           <input type="button" value="Exit">'; 
    

    回答

    16

    您可以使用\來指示該行尚未完成。

    var h= '<label>Hello World, Welcome to the hotel</label> \ 
           <input type="button" value="Visit Hotel"> \ 
           <input type="button" value="Exit">'; 
    

    注:當您使用\,在下面一行的空白也將是字符串的一部分,這樣

    console.log(h); 
    

    輸出

    <label>Hello World, Welcome to the hotel</label>    <input type="button" value="Visit Hotel">    <input type="button" value="Exit"> 
    

    最好的方法是使用Mr.Alien在評論部分concatenat中提出的方法E中的字符串,這樣

    var h = '<label>Hello World, Welcome to the hotel</label>' + 
           '<input type="button" value="Visit Hotel">' + 
           '<input type="button" value="Exit">'; 
    
    console.log(h); 
    

    輸出

    <label>Hello World, Welcome to the hotel</label><input type="button" value="Visit Hotel"><input type="button" value="Exit"> 
    
    +0

    +1或者如果你想在輸入中輸入一個輸入,像' \ n \ n '; – ncm

    +0

    @imsiso這看起來像HTML。他爲什麼要追加'\ n'? :) – thefourtheye

    +0

    +1或者他甚至可以連接像http://jsfiddle.net/pQYjd/ –

    7

    @thefourtheye答案是完美的,但如果你願意,你也可以使用串聯這裏,因爲有時\會誤導,因爲你會覺得這些是文字字符..

    var h = '<label>Hello World, Welcome to the hotel</label>'; 
        h += '<input type="button" value="Visit Hotel"> '; 
        h += '<input type="button" value="Exit">'; 
    
    console.log(h); 
    

    Demo

    相關問題