如何在没有id的情况下将jQuery元素传递给JavaScript函数?

时间:2014-03-21 15:28:06

标签: javascript jquery

HTML:

<div class="myClass">abc</div>
<div class="myClass">def</div>
<div class="myClass">ghi</div>
<div class="myClass">jkl</div>
<div class="myClass">mno</div>

jquery的:

$('.myClass').on('click',function() {
    // do stuff in jQuery ...
    // also select text using a pure JavaScript function like so:
    selectElementText(el);
    // obviously a `$(this)` won't work.
    // A `document.getElementById('myId')` will work, but I don't know how to get it
});

javascript选择文字功能(通过https://stackoverflow.com/a/2838358/834525):

function selectElementText(el, win) {
    win = win || window;
    var doc = win.document, sel, range;
    if (win.getSelection && doc.createRange) {
        sel = win.getSelection();
        range = doc.createRange();
        range.selectNodeContents(el);
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (doc.body.createTextRange) {
        range = doc.body.createTextRange();
        range.moveToElementText(el);
        range.select();
    }
}

如何将文档元素传递给此函数?

3 个答案:

答案 0 :(得分:3)

使用document关键字:

 selectElementText(document, window);
                     ^         ^        
                     ^          --- the window as in case of the function (optional)
                     ^--- the document as an argument which you want to pass

修改

感谢@A。沃尔夫,它应该是selectElementText(this);

答案 1 :(得分:3)

您应该使用:

selectElementText(this);

将DOM节点作为参数传递给selectElementText()函数。 ;)

答案 2 :(得分:1)

只需使用this,而不是$(this),如下所示:selectElementText(this);