2010-07-10 66 views

回答

7

您可以使用setAttribute或直接設置屬性。無論哪種方式,setAttribute是標準的DOM方式。

el.onclick = function() { 
    var t = document.getElementById('blah'); 

    // first way 
    t.src = 'blah.jpg'; 
    t.title = 'new title'; 
    t.alt = 'foo'; 

    // alternate way 
    t.setAttribute('title', 'new title'); 
    t.setAttribute('alt', 'new alt'); 
    t.setAttribute('src', 'file.jpg'); 
} 
+2

兩種方式都是絕對的標準。在DOM級別1 HTML中指定了'src' /'alt' /'title'。我會在'setAttribute'上推薦這些屬性,因爲訪問這些屬性的讀取要清晰得多,並且在IE中對於getAttribute' /'setAttribute'存在嚴重的錯誤,其中DOM屬性與HTML屬性不同。 – bobince 2010-07-10 21:40:42

+0

我個人使用DOM 0風格的直接屬性設置自己,是的,有錯誤。 – 2010-07-10 21:41:48

+0

謝謝你對這個問題bobince的額外澄清。 – computersaurus 2010-07-19 13:07:52

3
img.onclick = function() { 
    // old fashioned 
    img.src = "sth.jpg"; 
    img.alt = "something"; 
    img.title = "some title"; 
    // or the W3C way 
    img.setAttribute("src", "sth.jpg"); 
    img.setAttribute("alt", "something"); 
    img.setAttribute("title", "some title"); 
}​; 

注意:無論您使用的是隻要你處理的標準屬性之一。

+0

在瀏覽器兼容性方面是「老式」和「W3C」方式一樣嗎? – computersaurus 2010-07-10 20:59:18

+1

在這個有限的情況下,是的,但總的來說不是,IE在'getAttribute' /'setAttribute'方面有很多問題,所以如果可能的話,你應該避免**這些方法。 NB。在很多情況下屬性和屬性是不同的東西!在這種情況下,設置'.src'時的行爲與設置屬性'src'相同,但讀取它時將返回屬性指向的完整URL,這對於相對URL是不同的。 (由於上述的錯誤,在IE中不會發生這種情況。) – bobince 2010-07-10 21:42:07

+0

@computersaurus bobince,是正確的。 IE實現有幾個錯誤。我知道的是'src/href' url的相對性,'''','style'和'class'。 – galambalazs 2010-07-10 22:32:03

4

在完全相同的方式..

document.getElementById('main_image_id').title = 'new title' 
document.getElementById('main_image_id').alt = 'new alt'