2012-08-16 62 views
-1

我在使用JQuery中的.html()方法嘗試插入空間時遇到問題。 以下是我的代碼:如何在html中插入空格?

html += '<td >'+description+". "+location; 
html += +" "+position; 
html += +" &nbsp; "+side+'</td>'; 
$('#tempResult').html(html); 

我得到的結果如下: Green Tint. 0FrontNaNRight

回答

9

從字符串中刪除+操作。 +=負責字符串連接,因此額外的+符號只是試圖使字符串爲正(導致解釋器將其更改爲NaN - 不是數字)。

a += b是說a = a + b的「簡寫方式」(或許是簡化)。

html += '<td >'+description+". "+location; 
html += " "+position; 
html += " &nbsp; "+side+'</td>'; 
$('#tempResult').html(html); 
+1

我的不好,我試了很多,但沒有注意到額外的加號。非常感謝@nbrooks,它的工作原理:) – Leejoy 2012-08-16 22:00:19

1

+ = +位正在做一些類型轉換。擺脫第二+。

構建html的另一種方法是通過數組和連接。舉一個例子:

var description = 'DESCRIPTION', 
    location = 'LOCATION', 
    position = 'POSITION', 
    side = 'SIDE', 
    html = [ 
     '<td>' + description, 
     '. ' + location, 
     ' ' + position, 
     ' ' + side, 
     '</td>' 
    ]; 

$('#tempResult').html(html.join(''));