2011-07-23 3 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( 'スクリプト').next( 'フォーム')IDを – Cristian

+0

@Cristian:あなたが好きなものそれは常に最善の解決策ではないことに注意して – Ibu

1

また、スクリプトタグに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 + '".'); 
    } 
});