如何使用jQuery从click或id中获取所有属性?

时间:2017-06-17 12:24:27

标签: javascript jquery html css

我想知道如何在点击事件

中获取类或id的所有属性

意思是,假设我有类和id:

.sample {
    margin: 10px;
    color: #000;
    padding: 5px;
    border: 1px solid #4073ff;
}

#test {
    background: url(../sample.jpg) 20px 20px no-repeat cover red;  
}

现在点击事件我想要所有

类属性打印如下

<div id="cProperties">
  <h6>All properties from class comes here</h6>

  margin = 10px
  color = #000
  padding = 5px
  font-size = 60px
  border size = 1px 
  border style = solid
  border color = #4073ff

</div>

和id属性打印如下

<div id="iProperties">
    <h6>All properties from id comes here</h6>

    background url = url(../sample.jpg)
    top = 20px 
    center = 20px
    repeteation = no-repeat 
    attachment = cover
    color = red  

 </div>

fiddle

1 个答案:

答案 0 :(得分:1)

您可以使用jquery .css方法检索属性。

希望此代码段有用

&#13;
&#13;
$(".sample").click(function() {
  var html = [],
    x = $(this).css([
      "margin", "padding", "color", "border"
    ]);

  $.each(x, function(prop, value) {
    html.push(prop + ": " + value);
  });

  $("#result").html(html.join("<br>"));


})
&#13;
.sample {
  margin: 10px;
  color: #000;
  padding: 5px;
  border: 1px solid #4073ff;
}

#test {
  background: url(../sample.jpg) 20px 20px no-repeat cover red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<button class="sample">Click</button>
&#13;
&#13;
&#13;