2015-09-06 28 views
1

當我使用以下命令:如何設置一個空白值的屬性?

myElement.setAttribute('data-title', title); 

其中title是空白的我沒有得到一個空白的屬性。我得到一個沒有價值的屬性。

有沒有辦法使用JavaScript或jQuery獲得空白屬性?我問,因爲如果我不能那麼我後來引用屬性的代碼將變得複雜,以處理沒有價值的可能性。

+2

什麼是空白的屬性,沒有值 – sahbeewah

+1

屬性之間的區別@SteveC你想做些什麼? –

+0

這個問題不是我認爲的問題。謝謝大家。對不起,浪費你的時間。我使用attr()來取回屬性,但在錯誤的對象上。這總是很簡單。 – SteveC

回答

1

的setAttribute是本地函數。

var myElement = document.getElementById("myId"); 

myElement.setAttribute('data-title', "") 

myElement.getAttribute('data-title'); // you get : "" 

myElement.getAttribute('data-test'); // you get : null 


if (myElement.getAttribute('data-title') !== "" && myElement.getAttribute('data-title') !== null) 
    console.log("not empty"); 

如果你想使用jQuery prefere,ATTR:

var $myElement = $("#myId"); 

$myElement.attr("data-title", ""); 

$myElement.attr("data-title"); // you get : "" 

$myElement.attr("data-test"); // you get : undefined 

if (myElement.getAttribute('data-title') !== "" && typeof(myElement.getAttribute('data-title')) !== "undefined") 
    console.log("not empty"); 
+0

謝謝。你完全正確,但這不是我看起來的樣子(見上文)。 – SteveC

1

您應該使用ATTR

,如:

myElement.attr('data-ttitle','') 

檢索:

var data = myElement.attr('data-ttitle') 

參考here

+0

對不起。我應該提到我嘗試過。同樣的結果。 – SteveC

+0

當屬性爲空時,您將像空字符串一樣檢索,如果沒有屬性,則將檢索爲未定義。 @SteveC –