使用 jQuery 查找粘贴的内容是 html 还是纯文本
find if a pasted content is html or plain text using jQuery
我试图在将粘贴的内容添加到我的文本区域之前清除它。所以我使用回调,但如果我使用纯文本,则内容不会在回调中调用,函数中只会调用 html 文本。
有没有办法判断粘贴到文本区的内容是html内容还是普通内容?
当内容被粘贴到我的文本区域时,我正在使用这个
var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('text/html');
但上面的代码适用于 html。
但我需要知道内容是 html 还是纯文本。
let sPlain = 'plain text'
, sHtml = 'text <i>with tags</i>'
, wrapped_sp = `<div>${sPlain}</div>`
, wrapped_sh = `<div>${sHtml}</div>`
, w2t_sp = $(wrapped_sp).text()
, w2t_sh = $(wrapped_sh).text()
, isplain_sp = ( w2t_sp == sPlain )
, isplain_sh = ( w2t_sh == sHtml )
console.log( "%s is %stext/plain", sPlain, isplain_sp ? "" : "NOT " );
console.log( "%s is %stext/plain", sHtml, isplain_sh ? "" : "NOT " );
作为对原问题的具体回答:
let is_bufferText_plain = ( $(`<div>${bufferText}</div>`).text() == bufferText );
if( is_bufferText_plain ){
// do whatever is required if the bufferText content is text/plain
}else{
// do whatever is required if the bufferText content is text/html
}
我试图在将粘贴的内容添加到我的文本区域之前清除它。所以我使用回调,但如果我使用纯文本,则内容不会在回调中调用,函数中只会调用 html 文本。 有没有办法判断粘贴到文本区的内容是html内容还是普通内容? 当内容被粘贴到我的文本区域时,我正在使用这个
var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('text/html');
但上面的代码适用于 html。 但我需要知道内容是 html 还是纯文本。
let sPlain = 'plain text'
, sHtml = 'text <i>with tags</i>'
, wrapped_sp = `<div>${sPlain}</div>`
, wrapped_sh = `<div>${sHtml}</div>`
, w2t_sp = $(wrapped_sp).text()
, w2t_sh = $(wrapped_sh).text()
, isplain_sp = ( w2t_sp == sPlain )
, isplain_sh = ( w2t_sh == sHtml )
console.log( "%s is %stext/plain", sPlain, isplain_sp ? "" : "NOT " );
console.log( "%s is %stext/plain", sHtml, isplain_sh ? "" : "NOT " );
作为对原问题的具体回答:
let is_bufferText_plain = ( $(`<div>${bufferText}</div>`).text() == bufferText );
if( is_bufferText_plain ){
// do whatever is required if the bufferText content is text/plain
}else{
// do whatever is required if the bufferText content is text/html
}