如何使用Jquery查找最近的父元素属性值
I am facing a problem on getting the nearest parent element attribute value using Jquery. Can anyone help me on this. My element structure is as below,
<ul class="Someclass">
<li><span id=3 class="heading"></span>
<ul>
<li>
<ul> <li><span ><button onclick= "redirect()"></button></span</li>
<ul>
</li>
</ul>
</li>
<ul>
<script type="text/javascript">
function redirect() {
alert(....)
}
</script>
In the above code when i click that element having onclick
event i want to get the value as 3 in alert()
which is in the element having the class heading. The above code is in for loop so it will have more code like this in a same page.
我在使用 Jquery strong>获取最近的父元素属性值时遇到问题。 谁可以帮我这个事。 我的元素结构如下, p>
在上面的代码中,当我点击具有
&lt; ul class =“Someclass”&gt;
&lt; li&gt;&lt; span id = 3 class =“heading”&gt;&lt; ; / span&gt;
&lt; ul&gt;
&lt; li&gt;
&lt; ul&gt; &lt; li&gt;&lt; span&gt;&lt; button onclick =“redirect()”&gt;&lt; / button&gt;&lt; / span&lt; / li&gt;
&lt; ul&gt;
&lt; / li&gt;
&lt; ; / ul&gt;
&lt; / li&gt;
&lt; ul&gt;
&lt; script type =“text / javascript”&gt;
function redirect(){
alert(....)
}
&lt; ; / script&gt;
code> pre>
onclick code>事件的元素时,我希望在 alert() code>,它位于具有标题 strong>类的元素中。 上面的代码是for循环的,因此在同一页面中会有更多这样的代码。 p>
div>
With your current code, pass the clicked element reference to the function like
<button onclick= "redirect(this)">asdf</button>
then
function redirect(el) {
alert($(el).closest('.Someclass > li').children('span').attr('id'))
}
Demo: Fiddle
Bu a more recommended way will be is to use jQuery event handlers like
<button class="redirect">asdf</button>
then
jQuery(function($){
$('.Someclass .redirect').click(function(){
alert($(this).closest('.Someclass > li').children('span').attr('id'))
})
})
Demo: Fiddle
This should do it.
alert($(this).closest('.heading').attr('id'));
$(".someclass li").click(function(){
$(this).closet('.heading').attr('id');
})
could you pass it on as a parameter to your redirect function? You'd somehow hold that value in a variable in your loop.
Give this Try
function redirect(elem) {
alert($(elem).closest('.Someclass > li').children('span').attr('id'))
}
Change Markup to this:
<li><span><button onclick= "redirect(this)"></button></span</li>
this
will reffer to the current object in DOM
By wrapping elem
in $(elem)
will convert it to jQuery object then you can traverse to the closest and find span
You can also filter that span
with .children('span:first')
I got a solution if you can change the id
and class
to parent li
More about parent selector
Jquery
function redirect(elem) {
var myid = $(elem).parents(".heading").attr("id");
alert(myid);
}
HTML
<ul class="Someclass">
<li id="3" class="heading">
<ul>
<li>
<ul> <li><span ><button onclick="redirect(this)" id="haha">Go</button></span</li>
<ul>
</li>
</ul>
</li>
<ul>