Get the current jQuery selector string?

前端 未结 8 1922
北恋
北恋 2020-12-01 18:00

When calling a custom plugin, how can I get the current selector string?

$(\'my_selector p\').my_plugin();

Would like to output my_se

相关标签:
8条回答
  • 2020-12-01 18:43

    Extending to kevinmicke's answer : You can get the selector in your event object that you pass on callback functions.

    In callback functions

    event.handleObj.selector
    

    Example:

    You'll get the selector string in e.handleObj.selector

        $( '.container' )
        .on('change', 'select.mySelector', function (e) {
            console.log(JSON.stringify(e));
            $('.selector').text(e.handleObj.selector);
            $('.value').text($(this).val());
        });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container">
    
      <select class="mySelector">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>
      <h3>Your Selector: <span class="selector"></span></h3>
      <h3>Selected Value: <span class="value"></span></h3>
      
    </div>

    Console Log gives an object like this:

    {
        // ...skipped lines
        "handleObj": {
            "type": "change",
            "origType": "change",
            "guid": 1,
            "selector": "select.mySelector",
            "needsContext": false,
            "namespace": ""
        }
    }
    
    0 讨论(0)
  • 2020-12-01 18:47

    You can use selector property:

    $('my_selector p').selector // my_selector p
    

    version deprecated: 1.7, removed: 1.9

    0 讨论(0)
提交回复
热议问题