2012-08-15 54 views
1

數據屬性是我的新東西,只是意識到我需要轉義空間,逗號等。任何人都可以給我一些關於我的方法的建議嗎?以下是我的代碼:如何在HTML5數據屬性中轉義

#A list holds all the strings to be sent to data-attribute, 
#the sequence and length of the list is dynamic, determined by the user 
#(That's why I need to find a way to escape automatically. 

Apt_p = [] 
Apt_p.append('Relative to planting') 
Apt_p.append('Relative to harvest') 
Apt_p_j=json.dumps(Apt_p) #convert everything into JSON for future usage 

#I think below is the place to let escape happen. 
html = """<td id="Apt_p_j" data-val=%s></td>""" %(Apt_p_j) 

回答

4

將您的屬性值放在雙引號內,因此您不必擔心轉義空格。然後就像逃離引號中的任何其他屬性一樣逃避它。你的web框架應該有一個功能。

+0

我向數據屬性(data-val =「%s」)添加了雙引號,但現在返回的是'['。但後來我添加了單引號(data-val ='%s')。有用!謝謝! – 2012-08-15 19:37:10

+0

我確實使用了Firebug,發現雙引號不起作用。 – 2012-08-15 19:47:11

+0

我不知道fire bug是否讓你看到DOM的實際源或目前的狀態。這並不是說雙引號不起作用:通常它們工作正常,但顯然忘記了在你的json字符串中轉義雙引號。 – 2012-08-15 19:48:43