例如:
<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>
由于
答案 0 :(得分:1)
试试这个:
var form = $('script[src="getbelowelement.js"]').next();
但我建议使用表单id:
var form = $('#IamTheNext');
答案 1 :(得分:1)
你也可以尝试给脚本标签一个id。
答案 2 :(得分: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 + '".');
}
} );