使用jquery获取函数前的id值

时间:2017-05-19 10:32:14

标签: javascript jquery

$(document).ready(function(){
    $("#test").validate();

    function validate(){
       var x= //do some code it will return #test
       alert(x);
    }
});

我想要值test or #test如何获得它 怎么办?

1 个答案:

答案 0 :(得分:1)

// first, extend jquery with `validate` method
$.fn.validate = function() {
  var isValid = this.attr('id') === 'test'
  return isValid
}

    
$(document).ready(function(){    
  if ($("#test2").validate()) {
    console.log('#test is valid')
  }

  if($(".other").validate()) {
    console.log('#other is valid')  
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="test2">bla bla bla<div>
<div class="other" id="test">bla bla<div>