2011-07-23 77 views
0

例如:在jQuery中獲取就緒函數代碼下面的元素?

<script> 
$(document).ready(function() { 
    alert($(this).getBelowElementToThisScript('form').id); 
}); 
</script> 
<form id="IamTheNext"></form> 
<form id="Iamnot"></form> 

此代碼應顯示此消息:IamTheNext

此外,該解決方案需要用這個例子太工作:

<script src="getbelowelement.js"></script> 
<form id="IamTheNext"></form> 
<form id="Iamnot"></form> 

感謝

回答

1

嘗試這個:

var form = $('script[src="getbelowelement.js"]').next(); 

但我會建議使用的形式ID:

var form = $('#IamTheNext'); 
+0

這並不是說,我喜歡這樣的事情:$(本).closest(「腳本」)。接下來(「形式」)ID – Cristian

+0

@Cristian:請注意,你喜歡什麼並不總是最好的解決辦法 – Ibu

1

您也可以嘗試給script標籤的ID。

0

這種方法是危險的;腳本不應該太依賴它在頁面中的位置。

這就是說,在Firefox和Chrome以下工作和應在主流瀏覽器工作(需要您自擔風險使用)。

See it in action at jsBin.<script> ...<script src="...">方法顯示在同一頁中。

$(document).ready(function() { 
    invocationsOfThis = (typeof invocationsOfThis == 'number') ? invocationsOfThis + 1 : 1; 
    var scriptTags  = document.getElementsByTagName ('script'); 
    var thisScriptTag = null; 

    //--- Search scripts for scripts of this type. 
    for (var foundCnt = 0, J = 0, L = scriptTags.length; J < L; ++J) 
    { 
     /*--- Since the script can be either inline or included, search 
      both the script text and the script src link for our unique 
      identifier. 
     */ 
     var thisTag  = scriptTags[J]; 
     var scriptCode = thisTag.innerText || thisTag.textContent; 
     var scriptSrc = thisTag.src; 

     //--- IMPORTANT, change pastebin.com to the filename that you use. 
     if (/invocationsOfThis/i.test (scriptCode) || /pastebin.com/i.test (scriptSrc)) 
     { 
      //--- Found a copy of this script; is it the right one, based on invocation cnt? 
      foundCnt++; 
      if (foundCnt == invocationsOfThis) { 
       thisScriptTag = thisTag; 
       break; 
      } 
     } 
    } 

    if (thisScriptTag) { 
     //--- Get the target node. 
     var nextForm  = $(thisScriptTag).next ('form'); 
     var nextFormId  = nextForm.attr ('id'); 

     //--- Act on the target node. Here we notify the user 
     nextForm.text ('This is form: "' + nextFormId + '".'); 
    } 
}); 
相關問題