実現したいこと
次のように<p>
を<textarea>
に置換しています。後に<textarea>
の入力値が変更されたかどうかを判定したいです。
html
1<p>私は "太郎" です</p> 2 3<script> 4// p を textarea に置換 5const val = $('p').text(); 6const placeholder = htmlsce(val); 7$('p').replaceWith( `<textarea class="inp_name" placeholder="${placeholder}">${val}</textarea>` ); 8</script>
発生している問題
後に<textarea>
の入力値が変更されたかどうかを判定したいので、初期値をplaceholder
にセットしておき「<textarea>
の入力値 === placeholder
の値」での比較をしているのですが、
変更がないのにも関わらず「false」になってしまいます。
該当のソースコード
全体のソースコードはこちらで、isSame
が「false」となるのが問題です。
https://jsfiddle.net/moch3pyt/
html
1<p>私は "太郎" です</p> 2 3<script> 4// HTML特殊文字変換(通常文字 → 特殊文字) 5var htmlsce = (function() { 6 const map = {' ':' ','<':'<','>':'>','&':'&','"':'"',"'":''','©':'©'}; 7 return function(text, charset) { 8 charset = charset && charset.replace(/([\x00-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F])/g, '\\$&') || ''; 9 return text.replace(new RegExp('[ <>&"\'©'+charset+']', 'g'), function(match) { 10 if (map.hasOwnProperty(match)) { 11 return map[match]; 12 } else { 13 return '&#'+match.charCodeAt(match)+';'; 14 } 15 }); 16 }; 17})(); 18 19// HTML特殊文字変換(特殊文字 → 通常文字) 20var htmlscd = (function() { 21 const re = /&#x([0-9A-Fa-f]+);|&#(\d+);|&\w+;/g; 22 const map = {' ':' ','<':'<','>':'>','&':'&','"':'"',''':"'",'©':'©'}; 23 return function(text) { 24 return text.replace(re, function(match, p1, p2) { 25 if (match.charAt(1) == '#') { 26 // 数値文字参照 27 if (match.charAt(2) == 'x') { 28 return String.fromCharCode(parseInt(p1, 16)); 29 } else { 30 return String.fromCharCode(p2-0); 31 } 32 } else if (map.hasOwnProperty(match)) { 33 // 定義済み文字実体参照 34 return map[match]; 35 } 36 return match; 37 }); 38 }; 39})(); 40 41// p を textarea に置換 42const val = $('p').text(); 43const placeholder = htmlsce(val); 44$('p').replaceWith( `<textarea class="inp_name" placeholder="${placeholder}">${val}</textarea>` ); 45 46// 「placeholderの初期値」と「textareaの入力値」が同じかどうか 47const inpName = $('.inp_name').val(); 48const iniName = htmlscd( $('.inp_name').attr('placeholder') ); 49const isSame = inpName === iniName; 50console.log( inpName ); // 私は "太郎" です 51console.log( iniName ); // 私は "太郎" です 52console.log( isSame ); // false 53</script>
試したこと
ご覧のようにコンソール画面で確認しており、明らかにinpName
もiniName
も同じ値に見えます。
つまりHTML特殊文字変換の関数はいずれも正常に思われます。
ではなぜ「===」での比較が「false」になるのか疑問です。
JavaScript
1console.log( inpName ); // 私は "太郎" です 2console.log( iniName ); // 私は "太郎" です 3console.log( isSame ); // false
シンプルに以下にしても「fales」でした。(itagagakiさんのご指摘により訂正)
シンプルに以下にしたら「true」でした。
JavaScript
1const text = '私は "太郎" です'; 2const sce = htmlsce(text); 3const scd = htmlscd(sce); 4const isSame = scd === text; //(itagagakiさんのご指摘により訂正) 5 6console.log( sce ); // 私は "太郎" です 7console.log( scd ); // 私は "太郎" です 8console.log( isSame ); // true
また<textarea>
ではなくcontenteditable=true
への置換も試みてみたのですが、細かい仕様に対処できず断念致しました。
後に<textarea>
の入力値が変更されたかどうかを判定するためには、上記の流れのどこを直すべきでしょうか?
回答2件
あなたの回答
tips
プレビュー