每个,功能和数组

时间:2015-04-02 22:05:09

标签: javascript jquery

我有几个元素,我想要一个函数来获取每个元素的宽度和偏移量。我想保存每个元素的两个值,这样我就可以从函数外部访问它并做一些事情。我试过这个代码,但我卡住了。 THX。

$(document).ready(function() {
	
	$("div>div").off("click").click(function() {			
      var checkWidth ;
	  var checkLeft ;
	  function checkPosition() {		  
	    $("div>div").each(function() {
          checkWidth = $(this).width();
	      checkLeft = $(this).offset().left;
        });			
        return [checkWidth, checkLeft];
	  }
	 var test = checkPosition()	
	 alert(test);		    		
	});
	
	// if( width of second element is # && offset of third element is # ) {
	// do some thing ;
  ¨ //  }
	
})
div div{
    position: relative;
	height: 100px;
	width: 100px;		
	margin-top: 20px;
}
.rectangle1{ 
	background-color: black;
	width: 100px;
	left: 10px;
}
.rectangle2{
	background-color: red;
	width: 200px;
	left: 30px;
}	
.rectangle3{ 
	background-color: black;
	left: 60px;
	width: 300px; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<head>
</head>

<body>
  <div>  
    <div class="rectangle1"></div>
    <div class="rectangle2"></div>
    <div class="rectangle3"></div>
  </div>
</body>

2 个答案:

答案 0 :(得分:0)

将数组定义为函数以使其成为全局数据并使用每个(索引)来正确设置数组的值:

&#13;
&#13;
$(document).ready(function() {
    var myarray=[];
    $("div>div").off("click").click(function() {        
        var checkWidth ;
        var checkLeft ;
      function checkPosition() {          
        $("div>div").each(function(index) {
          checkWidth = $(this).width();
          checkLeft = $(this).offset().left;
          myarray[index]=[checkWidth,checkLeft];
        });         
        return myarray;
      }
     var test = checkPosition() 
     alert(test);                   
    });

    //if( width of second element is # && offset of third element is # ) {}
    // if (myarray[1][0]==130 && myarray[2][1]==120){}
    // as you have a two dimensional array and javascript array starts from 0:
    // myarray[n][0] will return the width of n+1(th) element
    // myarray[n][1] will return the offset of n+1(th) element
    

})
&#13;
div div{
    position: relative;
	height: 100px;
	width: 100px;		
	margin-top: 20px;
}
.rectangle1{ 
	background-color: black;
	width: 100px;
	left: 10px;
}
.rectangle2{
	background-color: red;
	width: 200px;
	left: 30px;
}	
.rectangle3{ 
	background-color: black;
	left: 60px;
	width: 300px; 
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div>  
    <div class="rectangle1"></div>
    <div class="rectangle2"></div>
    <div class="rectangle3"></div>
  </div>
</body>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我为答案创建了一个jsfiddle。在这里查看https://jsfiddle.net/dj2jdzrp/

    var divProperties;
    $("#outerDiv > div").click(function(e) { 
    divProperties = {"offset" : $(this).offset() , "width" : $(this).width() }
    alert('anchor clicked!'+ divProperties.offset.left + 'width'+         divProperties.width); 
    });