获取在css-selector上调用的插件中的元素ID

时间:2017-07-31 09:51:29

标签: javascript jquery plugins

我有一个基本问题。我有这个例子jquery-plugin,我希望在所有具有特定css选择器(.myDiv)的div上运行:



(function($) {

  $.fn.testt = function(options) {
    console.log(this.id);
    console.log($(this).attr('id'));
  };

}(jQuery));


$(".myDiv").testt({
  'thickness': 3,
  'color': '#ccc'
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myDiv" id="myfirstDiv">blablabla</div>
&#13;
&#13;
&#13;

如何获取div的ID?我的代码总是返回undefined

2 个答案:

答案 0 :(得分:1)

thistestt()插件方法中的jQuery对象,您可以使用各种jQuery方法。

如果你有多个元素使用.each()并且在迭代器方法中

(function($) {
  $.fn.testt = function(options) {
    //Here this refers to jQuery object
    this.each(function() {
      //Here, this refers to underlying DOM element, so you can use various method
      console.log(this.id); 
    })    
  };
}(jQuery));


$(".myDiv").testt({
  'thickness': 3,
  'color': '#ccc'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myDiv" id="myfirstDiv">blablabla</div>
<div class="myDiv" id="myfirstDiv2">blablabla</div>
<div class="myDiv" id="myfirstDiv3">blablabla</div>

答案 1 :(得分:1)

使用此代码:

此处为ID演示:https://output.jsbin.com/pasequp

<强> HTML:

public static void main(String[] args){
    File rootDir = new File(System.getProperty("user.home"));
    String tmp = "";
    for(File f : allFilesInDirectory(rootDir)){
         tmp += allText(f);
    }
    System.out.println(tmp);
}

<强> JavaScript的:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="myDiv" id="myfirstDiv">blablabla</div>
<div class="myDiv" id="myfirstDiv1">blablabla</div>
<div class="myDiv" id="myfirstDiv2">blablabla</div>
</body>
</html>