如何选择< script>的父项元素 [英] how to select parent of <script> element
问题描述
<div id="scriptparent">
<script type="text/javascript">
$( /* select above <div> from <script> ... without id and div property */ )
</script>
</div>
从代码中的
,我在<div>
块中有一个<script>
块.我想从<script>
中选择<div>
,而没有id,class,name选择器.我该如何实现?
from the code I have a <script>
block inside <div>
block. I'd like to select <div>
from <script>
without id, class, name selectors. How can I achieve this?
推荐答案
如果代码如您所显示的那样,并且在构建DOM时立即运行,则可能能够用document.body.lastChild
做某事.
If the code is as you've shown it and so it's running right away, as the DOM is being built, you may be able to do something with document.body.lastChild
.
因此,对您的问题的简短回答是:
So the short answer to you question is:
var div = $(document.body.lastChild).closest('div');
在测试中(在Chrome上),我有点偏执,document.body.lastChild
是div
,但使用
I'm being a bit paranoid there, in my tests (on Chrome), document.body.lastChild
is the div
, but by using closest
I deal with the possibility it could be script
on some engines.
The long answer is an example: Live Copy | Source
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Last Element ID</title>
<script>
function setUpParentDiv() {
var div = $(document.body.lastChild).closest('div');
switch (div.attr("id")) {
case "div1":
div.css("color", "blue");
break;
case "div2":
div.css("color", "green");
break;
}
}
</script>
</head>
<body>
<div id="div1">
I'm div1
<script>
setUpParentDiv();
</script>
</div>
<div id="div2">
I'm div2
<script>
setUpParentDiv();
</script>
</div>
</body>
</html>
这篇关于如何选择< script>的父项元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!