如何选择当前的Divs ID名称,Width和Height属性?

时间:2014-08-19 06:52:43

标签: javascript jquery

在这里,我有四个不同宽度,高度和颜色的div,它们显示和隐藏在相应的按钮点击上。我正在为div添加一个类“activeDiv”,以便我可以使用该选择器选择它。关键是 - 我想选择当前div的宽度,高度和id名称并存储它以便我可以用于进一步的目的,而不是每次都用选择器手动选择它们。当我尝试脚本提醒“null”时我有不知道该怎么做。找到下面的小提琴链接。

谢谢你的帮助。

4 个答案:

答案 0 :(得分:0)

试试这个:

$('button').click(function(){

   // Selecting the Current Div Width, Height and Id Name
   var currentDivWidth = $('.activeDiv').width();
   var currentHeight = $('.activeDiv').height();
   var currentDivId = $('.activeDiv').attr('id');

   alert($('.activeDiv').width());
});

答案 1 :(得分:0)

这是另一种方法

var div = $('div').not(':first').hide().end();

$('button').on('click', function()  { 
    var current = div.hide().eq($(this).index()).show();

    var id     = current.prop('id');
    var height = current.height();
    var width  = current.width();

});

FIDDLE

答案 2 :(得分:0)

您只需在活动类存在之前设置一次变量,并且在单击时永远不会更新它,因此变量永远不会被设置。

如果您尝试这样的事情,它应该有效:http://jsfiddle.net/9ysez54j/

在您的点击功能中:

$('body').trigger('updateCurrent');

然后你可以得到这样的东西:

$('body').on('updateCurrent', function() {
    // Selecting the Current Div Width, Height and Id Name
    var currentDivWidth = $('.activeDiv').width();
    var currentHeight = $('.activeDiv').height();
    var currentDivId = $('.activeDiv').attr('id');
    alert(currentDivId);
});

答案 3 :(得分:0)

前几天我遇到了同样的问题。让我试着解释一下; 您正在选择具有尚不存在的类的div。因此,您需要在附加类后选择div。不是一个完美的解决方案,但它可能会帮助你。

function getWidth(currentDiv){
    var currentDivWidth = $(currentDiv).width();
    var currentHeight = $(currentDiv).height();
    var currentDivId = $(currentDiv).attr('id');
    alert(currentDivWidth);
}
//1.Hiding and Showing dive on button click
//2.Adding up a class "activeDiv" to the current Div so that I could select the current div with that class selector

$('#btn1').click(function(){
    $('#red').show().addClass('activeDiv');
    $('#green').hide();
    $('#yellow').hide();
    $('#blue').hide();  
    getWidth($('#red'));
});