當我使用以下命令:如何設置一個空白值的屬性?
myElement.setAttribute('data-title', title);
其中title
是空白的我沒有得到一個空白的屬性。我得到一個沒有價值的屬性。
有沒有辦法使用JavaScript或jQuery獲得空白屬性?我問,因爲如果我不能那麼我後來引用屬性的代碼將變得複雜,以處理沒有價值的可能性。
當我使用以下命令:如何設置一個空白值的屬性?
myElement.setAttribute('data-title', title);
其中title
是空白的我沒有得到一個空白的屬性。我得到一個沒有價值的屬性。
有沒有辦法使用JavaScript或jQuery獲得空白屬性?我問,因爲如果我不能那麼我後來引用屬性的代碼將變得複雜,以處理沒有價值的可能性。
的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");
謝謝。你完全正確,但這不是我看起來的樣子(見上文)。 – SteveC
什麼是空白的屬性,沒有值 – sahbeewah
屬性之間的區別@SteveC你想做些什麼? –
這個問題不是我認爲的問題。謝謝大家。對不起,浪費你的時間。我使用attr()來取回屬性,但在錯誤的對象上。這總是很簡單。 – SteveC