2013-12-11 34 views
0

我知道jQuery有.select();方法,问题是我可以得到这个选择的值吗?jQuery获取输入字段中高亮字符的值而不使用插件

http://api.jquery.com/select/

只要我需要得到里面的文字或输入框的强调字符值。

没有使用任何插件。

+0

可能的重复问题。看到这个问题/答案[http://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text](http://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text ) –

+1

[使用jQuery获取高亮显示的文本.select()?](http://stackoverflow.com/questions/12211964/get-highlighted-text-using-jquery-select) – Horen

+0

@霍伦感谢很多 – ProllyGeek

回答

1

HTML

<input type="text" name="textbox1" /> 

jQuery的

$(document).ready(function(){ 
    $('input[type="text"]').select(function() { 
     alert(window.getSelection()); 
    }); 
}); 
1

您可以使用.selectionStart和.selectionEnd。例如:http://jsfiddle.net/tonicboy/225B8/

<input type="text" name="foobar" id="foobar" /><button type="button">Show Value</button> 

$("button").click(function() { 
    var selected = getSelect($("#foobar")); 
    alert('highlighted text: ' + selected); 
}); 

function getSelect($el) { 
    var fullvalue = $el.val(), 
     el = $el.get(0); 

    return $el.val().substring(el.selectionStart, el.selectionEnd); 
}