最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to find the script tag's parent - Stack Overflow

programmeradmin3浏览0评论

How to find an element relative to script's position? For instance, in the case below I would like getSelfParent to return the $('button') element

<button>
    <script>
        getSelfParent().click(function(){...});
    </script>
</button>

$(this).parent() did not work.

EDIT:

I want to avoid:

  • adding ID's anywhere
  • traversing whole tree every time I am looking for the self element

How to find an element relative to script's position? For instance, in the case below I would like getSelfParent to return the $('button') element

<button>
    <script>
        getSelfParent().click(function(){...});
    </script>
</button>

$(this).parent() did not work.

EDIT:

I want to avoid:

  • adding ID's anywhere
  • traversing whole tree every time I am looking for the self element
Share Improve this question edited Sep 13, 2011 at 11:19 Jakub M. asked Sep 13, 2011 at 10:20 Jakub M.Jakub M. 33.9k48 gold badges116 silver badges183 bronze badges 2
  • @a'r: this is the way I want to create buttons in my php – Jakub M. Commented Sep 13, 2011 at 10:25
  • 1 it's very likely that the script will always be inside a certain element so why not just give the element you want to access an ID and access it via $('#id')? – clem Commented Sep 13, 2011 at 10:26
Add a ment  | 

3 Answers 3

Reset to default 5
@Jakub M: this is the way I want to create buttons in my php.

Try to generate HTML|SCRIPT output as:

<button>
    <script id='RandomOrUniqueIdValue'>
        var script=document.getElementById('RandomOrUniqueIdValue');
        // var script=$('#RandomOrUniqueIdValue');
    </script>
</button>

I don't think there's really a way of accessing the parent element of a script tag, as a script is executed in reference to the window object, not the html tag it is in.

generally speaking, rather than copying and pasting the same/similar piece of javascript inside each button element, it would make more sense to just give them a class and access them in a single js function

you should do:

<button>
    <script type="text/javascript" id="myscriptToHide1">
        jQuery('#myscriptToHide1').parents('button').hide();
    </script>
</button>
发布评论

评论列表(0)

  1. 暂无评论