从 Jquery 中的 Div 类名称获取 Id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15780311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:47:29  来源:igfitidea点击:

Getting Id from Div Class Name in Jquery

javascriptjqueryhtml

提问by Shivkumar

this is my Html code

这是我的 Html 代码

<div class="span12" id="test" style="width: 810px;">
        <ul class="nav nav-tabs">
            <li class="active"><a href="/#tab1" data-toggle="tab">New Stream</a></li>
            <li><a id="addspan" href="/#C" data-toggle="tab">+</a></li>
        </ul>
        <div class="tabbable">
            <div class="tab-content" id="tabContent">
                <div class="tab-pane active" id="tab1">
                    @Html.Partial("_NewStreamPartial",Model)
                </div>

            </div>
        </div>
    </div>

this my javascript

这是我的 javascript

<script type="text/javascript">
    $(function () {
        var count = 2;
        $('#addspan').click(function () {
            var Id = $('.tab-pane active').attr('id');

          });
    });
</script>

I want to get Div Id whoes class name ".tab-pane active"(means i want to get active Div Id) how i can do this?

我想获得 Div Id whoes class name ".tab-pane active"(意味着我想获得活动 Div Id)我该怎么做?

回答by Adil

You can use dotto join classesin selector

您可以使用dot加入classes选择器

Change

改变

 var Id = $('.tab-pane active').attr('id');

To

 var Id = $('.tab-pane.active').attr('id');

回答by Chamika Sandamal

It should be like this,

应该是这样的

var Id = $('.tab-pane.active').attr('id');

You are using Descendant Selectorhere. but in your dom both classes are in same element. so you have to select by both classes.

您在这里使用后代选择器。但在你的 dom 中,两个类都在同一个元素中。所以你必须选择两个

回答by ravisolanki07

Try this :

尝试这个 :

 $('#addspan').click(function () {
           alert($('.tab-pane .active').attr('id'));
 });

回答by Ambrose Jesuraj

Try the following code

试试下面的代码

$("#addspan").click(function(){console.log($(this)[0].id);});

回答by itsstephyoutrick

You can get any HTML Attribute from an element with jQuery's .attr():

您可以使用 jQuery 从元素中获取任何 HTML 属性.attr()

$('.tab-pane.active').attr('id');

Similarly, you can also get the JS Object Property value using .prop():

同样,您也可以使用.prop()以下方法获取 JS 对象属性值:

$('.tab-pane.active').prop('id');

回答by Roger

You can try this

你可以试试这个

$('.tab-pane active').click(function () {
   var Id = $(this).attr('id');
});

Hope this helps

希望这可以帮助