获取子元素的id并使用jquery存储在变量中?

获取子元素的id并使用jquery存储在变量中?,jquery,attributes,element,Jquery,Attributes,Element,我基本上是想完全按照主题的建议去做,但我的警觉中有“未定义的”,我不完全确定为什么。我对jquery相当陌生,因此,我可能语法有误,但不确定从这里开始该怎么做。我将发布我的两次尝试,这两次尝试都会在警报中产生“未定义” //In my first attempt, I'm trying to get the id of the inner a tag <ul> <li id="l1" class="active"><a href="#

我基本上是想完全按照主题的建议去做,但我的警觉中有“未定义的”,我不完全确定为什么。我对jquery相当陌生,因此,我可能语法有误,但不确定从这里开始该怎么做。我将发布我的两次尝试,这两次尝试都会在警报中产生“未定义”

//In my first attempt, I'm trying to get the id of the inner a tag
<ul>
                <li id="l1" class="active"><a href="#c1">Samp 1</a></li>
                <li id="l2" class=""><a href="#c2">Samp 2</a></li>
                <li id="l3" class=""><a href="#c3">Samp 3</a></li>
        </ul>

var selected = $(".active).children("a").attr("id");
    alert(selected);

//In my second attempt, I'm trying to get the id of the currently selected li
    var selected = $(".active").attr("id");
    alert(selected);
//在我的第一次尝试中,我试图获取内部a标记的id
所选变量=$(.active).children(“a”).attr(“id”); 警报(选定); //在第二次尝试中,我尝试获取当前选定li的id 所选变量=$(“.active”).attr(“id”); 警报(选定);
锚的问题似乎是,您选择的锚都没有实际的ID。您的意思是说有可能
.attr(“href”)
吗?

在第一次尝试中,您得到了


如果您实际上想从

中获取
id
,那么您获取的属性是错误的(或者您的标记是错误的)。a标记中没有“id”属性。您具有“href”属性,因此如果您试图获取“href”的值,则应使用以下方法:

var selected = $(".active).children("a").attr("href");
    alert(selected);
否则,如果需要获取家长id,则应使用:

var selected = $(".active).attr("id");
    alert(selected);
您的
元素没有
id
,只有
href
。使用选择器而不是子函数可能会使代码更易于阅读

你是说
$(.active>a”).attr(“href”)


jQuery将返回jQuery集合中第一个元素的
id
属性。是否有另一个类为
活动的元素


我建议您尝试
$(“ul>li.active”).attr(“id”)

您缺少双引号。
var selected = $(".active).attr("id");
    alert(selected);
$(".active").children("a").attr("id");
$(".active").attr("id");