2014-03-06 103 views
1

我試圖讓一個#用於scrollTop函數,但我得到的是'undefined' 我哪裏出錯了?試圖得到一個元素的位置,但它總是'undefined'

<html><head><meta http-equiv=Content-Type content="text/html; charset=UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.1/jquery.mobile-1.4.1.min.css"> 
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script> 
<script src="http://code.jquery.com/mobile/1.4.1/jquery.mobile-1.4.1.min.js"></script> 
</head><body> 

<div data-role="page" id="page5" data-theme="c"> 
<BR><BR><BR><BR> 
<p><span id="1.11.13">1.11.13</span> Lots of text here... </p> 

<script> 
$(window).on('pageinit', function() { 
    console.log($('#1.11.13').css('top')); //undefined 
    console.log($('#1.11.13').position()); // undefined 
    //console.log($('#1.11.13').offset().top); = Uncaught TypeError: Cannot read property 'top' of undefined 
}); 

</script></div></body></html> 
+0

'$(文件)。在( 'pageinit''不是'$(窗口)。在(' pageinit''。 – Omar

回答

3

逃避它使用任何元字符(如!「#$%&「() * +,。/:; < =>?@ [] ^`{|}〜)作爲名稱的文字部分,必須用兩個反斜槓進行轉義:例如,一個id =「foo .bar「,可以使用選擇器$(」#foo \ .bar「)。

所以要麼逃脫特殊的cha racter:

$('#1\\.11\\.13') 

或使用:

var id="1.11.13"; 
$("[id='"+id+"']") 
+0

:)進入10K ... +1。順便說一句,它是一個很好的答案。 –

+0

woooooohoooooo ......終於進入10k.Thanks :) –

1

在選擇.指示類選擇,所以你需要躲避它,因爲在你的情況下,它是id值的一部分

你需要躲避.在ID

$('#1\\.11\\.13') 

演示:Fiddle

否則它會查找ID爲1和類的元素和13

<span id="1" class="11 13">1.11.13</span> 

演示:Fiddle

0

請注意,id開始用號碼無效HTML。

在你的情況,如果你想保持你的選擇,你可以通過\

$('#1\\.11\\.13') 
+0

所以你逃避它,因爲使用的數字.. :)只需將此行添加到您的答案,_因爲您正在使用選擇器內的元字符,你必須逃避它,使選擇器工作.._ –

相關問題