我有一個像屬性名稱,寬度的圖像。如何通過javascript找到圖像的屬性
現在我試圖得到一個不存在與圖像的屬性值。
var title = imgTemp.attributes("Title").value;
它給出錯誤,因爲參數Title
不存在。如何在分配之前檢查此信息?
我有一個像屬性名稱,寬度的圖像。如何通過javascript找到圖像的屬性
現在我試圖得到一個不存在與圖像的屬性值。
var title = imgTemp.attributes("Title").value;
它給出錯誤,因爲參數Title
不存在。如何在分配之前檢查此信息?
您可以使用getAttribute
:
var title = imgTemp.getAttribute('title');
如果沒有title屬性,它會返回null
。
您也可以直接訪問屬性作爲一個屬性:
var title = imgTemp.title;
然後它會返回一個空字符串,如果沒有title屬性存在,這意味着你將不得不如果標題相同的返回值屬性存在,但空,f.ex:<img title="">
使用element.hasAttribute()
,像這樣
if (imgTemp.hasAttribute('title')) {
// get it
}
不要使用attributes
http://reference.sitepoint.com/javascript/Node/attributes。
var title = domElement.title
沒有jQuery讓我傷心:( – Undefined
@Sam jQuery只是爲了得到一個屬性?真的嗎? – ManseUK