开发者

jQuery change() not triggering when pressing space?

开发者 https://www.devze.com 2023-01-10 21:40 出处:网络
In order to highlight spacing between Chinese characters I\'ve got this code function replaceSpaces(){

In order to highlight spacing between Chinese characters I've got this code

function replaceSpaces(){
    var segmented = $(this).val().replace(/\s/g, "<span>&emsp;</span>");
    $('#preview').html(segmented);
}
$(document).ready(function(){
    $('.tobesegmented').focus(replaceSpaces);
    $('.tobesegmented').change(replaceSpaces);
});

h开发者_开发百科owever, it does NOT trigger the change when I hit the space bar, only when i add text. Is there a way to trigger the replaceSpaces when a person hit's the space bar?

Bonus: Also, why does <span>&amp;emsp;</span> become <span>&amp;amp;emsp;</span>?


You can use the keyup event instead (or in addition), like this:

$('.tobesegmented').bind('focus keyup', replaceSpaces);

.bind() can also take multiple event names separated by a space, so illustrating that as well, shaving a bit of code off :)

For the bonus: because it gets HTML encoded for you, as another example, .text('&') on an element will actually render &amp; in the HTML :)

0

精彩评论

暂无评论...
验证码 换一张
取 消