How to select the text of a span on click?

前端 未结 4 2050
旧时难觅i
旧时难觅i 2021-01-31 18:19

I am looking for a way to select the text inside a span using jquery when the text is clicked on.

For example in the html snippet below, I want the text \"\\apples\\ora

4条回答
  •  自闭症患者
    2021-01-31 18:52

    A working demonstration : http://jsfiddle.net/dystroy/V97DJ/

    $('.unc_path').click(function (){
        var text = $(this).text();
        var $input = $('');
        $input.prop('value', text);
        $input.insertAfter($(this));
        $input.focus();
        $input.select();
        $(this).hide();
    });​
    

    The idea (see comment above) is to dynamically replace the span with an input, only cross-browser way I know to have selected text.

    Note that this is only half the road, as you probably want to deselect, style to remove border, etc.

    And I must also precise that an input, contrary to a span, cannot span on multiple lines.

    I don't think this could/should be used in a real application except in a very specific point.


    EDIT : new version : http://jsfiddle.net/dystroy/A5ZEZ/

    In this version the text comes back to normal when focus is lost.

    $('.unc_path').click(function (){
        var text = $(this).text();
        var $this = $(this);
        var $input = $('');
        $input.prop('value', text);
        $input.insertAfter($(this));
        $input.focus();
        $input.select();
        $this.hide();
        $input.focusout(function(){
            $this.show();
            $input.remove();
        });
    });​
    

提交回复
热议问题