[英]JavaScript variable out side function not retaining the value
我的下面的代碼有問題,我在使用onclick屬性調用下面的函數,然后檢查要傳遞的數據類型。 然后將其分配給函數外部的局部變量。 但是有些方法如何保存1個attr並在警報中顯示它,並將另一個顯示為undefined,然后當我單擊另一個attr時顯示它,第一個顯示為undefined。 我的js和HTML如下。
jQuery代碼:
<script>
var attr1 = null;
var attr2 = null;
function createLink(sportAttr) {
if($(sportAttr).attr("data-provider-sport-id") != typeof undefined && $(sportAttr).attr("data-provider-sport-id") !== false) {
attr2 = $(sportAttr).attr("data-provider-sport-id");
//alert(attr2);
}
if($(sportAttr).attr("data-main-sport-id") != typeof undefined && $(sportAttr).attr("data-main-sport-id") !== false) {
attr1 = $(sportAttr).attr("data-main-sport-id");
//alert(attr1);
}
alert(attr1 + " and second attr is " + attr2);
//it never reaches the next line because for some reason one of the attrs is always null
if(attr1 != null && attr2 != null) {
if(confirm("Are you sure you want to create this link")) {
}
}
}
</script>
HTML代碼:
<i data-provider-sport-id="9" onclick="createLink(this)">Music</i>
<b data-main-sport-id="17" onclick="createLink(this)">Music</b>
當我單擊第一個時,它顯示“未定義,第二個attr為9”。
當我單擊第二個按鈕時,它顯示“ 17,第二個屬性未定義”
有什么線索嗎?
此檢查不正確:
$(sportAttr).attr("data-main-sport-id") != typeof undefined
請參閱, typeof undefined
始終是字符串 'undefined'
(因為typeof始終返回字符串)。 除非數據屬性碰巧相同(即字符串'undefined'
否則此語句將為true。
因此,您的問題不是保留,而是由於if
語句配置錯誤而覆蓋值的事實。
要解決此問題,請使用以下未定義的檢查(您可能首先嘗試過此檢查) :
typeof $(sportAttr).attr("data-main-sport-id") !== 'undefined'
或者只使用未定義的普通比較,不帶typeof
(但這不夠穩健,因此使用typeof的直覺本身並不壞) :
$(sportAttr).attr("data-main-sport-id") !== undefined
您可以僅檢查Truthy值,而不是檢查屬性是否未定義且值不為false,如下所示:
var attr1 = null; var attr2 = null; function createLink(sportAttr) { if($(sportAttr).attr("data-provider-sport-id")) { attr2 = $(sportAttr).attr("data-provider-sport-id"); //alert(attr2); } if($(sportAttr).attr("data-main-sport-id")) { attr1 = $(sportAttr).attr("data-main-sport-id"); //alert(attr1); } alert(attr1 + " and second attr is " + attr2); //it never reaches the next line because for some reason one of the attrs is always null if(attr1 != null && attr2 != null) { if(confirm("Are you sure you want to create this link")) { } } }
希望這可以幫助!
首先,我建議您避免在HTML上設置onclick
,這不是一個好習慣。 另外,我還改善了您的代碼,請看以下內容:
JS:
$(document).ready(function(){
$('.myAction').on('click', function(){
createLink($(this).data('id'))
});
});
function createLink(sportAttr) {
if(typeof sportAttr !== 'undefined') {
alert(sportAttr);
}
}
HTML:
<i class="myAction" data-id="9" data-provider-sport-id="9">Music</i>
<b class="myAction" data-id="17" data-main-sport-id="17">Music</b>
基本上,這個想法是使一個泛型函數並嘗試減少代碼並使其更簡潔,同時您也沒有正確檢查undefined
。
if(typeof sportAttr !== 'undefined') {
alert(sportAttr);
}
希望對您有所幫助。
刪除typeof
運算符, typeof undefined
為"undefined"
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.