IE的document.getElementById混淆name和id属性的BUG(转)

本文介绍了一个在IE浏览器中出现的Bug,当页面上同时存在相同名称的name属性和id属性时,使用JavaScript通过ID选择器修改元素值可能会出现误操作。文章提供了两种解决方案。

前不久在做项目时遇见了一个BUG。说实话IE这BUG我百度出来08年就有了,竟然到现在都没改。。。。醉了!

<body> 
<script language="javascript"> 
function changeValue()  
{  
    var username = document.getElementById('username');  
    username.value = 'Whahaha';  
}  
</script> 
<form action="IE_BUG2.html" method="get"> 
<p>name:<input type="text" name="username" /></p> 
<p>name2:<input type="text" id="username" name="name" /></p> 
<p><input type="button" value="改变" onclick="changeValue();" /></p> 
</form> 
</body> 

 很简单的一段代码,看上去似乎没有任何错误。但是在IE下点击改变按钮后,被改变值的对象居然是第一个name属性为username的input对象,而不是第二个id属性为username的对象。难道IE会自动把没设过ID的标签自动设一个和name一样的ID?

 

不管怎么说,问题还是要解决,有2个方法:

方法一:尽量避免在页面中出现name与id属性相同的对象。

 

方法二:利用JavaScript的特点,重写document.getElementById!

package com.hey.fgh; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.speech.tts.TextToSpeech; import android.speech.tts.UtteranceProgressListener; import android.util.Log; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private WebView mWebView; private TextToSpeech tts; private boolean isSpeaking = false; private boolean isPaused = false; private int currentSentenceIndex = 0; private int currentCharIndex = 0; private String[] sentences; private String fullOriginalText; private List<NodeInfo> nodeInfoList = new ArrayList<>(); private final Handler handler = new Handler(); private SharedPreferences sharedPreferences; private boolean isTTSInitialized = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sharedPreferences = getSharedPreferences("TTSPreferences", MODE_PRIVATE); loadProgress(); initTextToSpeech(); setupWebView(); loadWebContent("file:///android_asset/index.html"); setupButtons(); } private void setupWebView() { mWebView = findViewById(R.id.mWebView); WebSettings settings = mWebView.getSettings(); settings.setJavaScriptEnabled(true); settings.setDomStorageEnabled(true); settings.setAllowFileAccess(true); settings.setAllowContentAccess(true); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { settings.setAllowUniversalAccessFromFileURLs(true); } mWebView.addJavascriptInterface(new TextNodeInterface(), "TextNodeInterface"); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { // 注入高亮工具函数 injectHighlightHelper(); // 延迟采集文本节点 handler.postDelayed(() -> collectTextNodes(), 1000); } }); } private void injectHighlightHelper() { String helperJs = "(function() {" + "if (window.createHighlightAtNodeByText) return;" + // 防止重复注入 "window.createHighlightAtNodeByText = function(targetText, localStart, localEnd) {" + " var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null);" + " var node;" + " while (node = walker.nextNode()) {" + " if (node.nodeType !== Node.TEXT_NODE || !node.parentNode || node.parentNode.nodeType === Node.ELEMENT_NODE && ['SCRIPT','STYLE'].includes(node.parentNode.tagName)) continue;" + " if (node.textContent.includes(targetText)) {" + " var text = node.textContent;" + " var before = text.substring(0, localStart);" + " var middle = text.substring(localStart, localEnd);" + " var after = text.substring(localEnd);" + " var parent = node.parentNode;" + " parent.innerHTML = '';" + " parent.appendChild(document.createTextNode(before));" + " var mark = document.createElement('mark');" + " mark.className = 'highlight';" + " mark.style.backgroundColor = 'yellow';" + " mark.style.color = 'black';" + " mark.textContent = middle;" + " parent.appendChild(mark);" + " parent.appendChild(document.createTextNode(after));" + " return;" + " }" + " }" + "};" + "})();"; mWebView.evaluateJavascript(helperJs, null); } private void collectTextNodes() { loadJsFromAssets("collect_text_nodes.js"); // 确保这个JS存在assets中 } private void loadJsFromAssets(String fileName) { try { InputStream is = getAssets().open(fileName); byte[] buffer = new byte[is.available()]; is.read(buffer); is.close(); String jsCode = new String(buffer, StandardCharsets.UTF_8); mWebView.evaluateJavascript(jsCode, null); } catch (Exception e) { Log.e(TAG, "加载JS失败: " + fileName, e); Toast.makeText(this, "脚本加载失败", Toast.LENGTH_SHORT).show(); } } private void splitSentences(String rawText) { String filteredText = rawText.replaceAll("[\\r\\n]+", "\n").trim(); List<String> sentenceList = new ArrayList<>(); String[] paragraphs = filteredText.split("\\n\\s*\\n|\\r\\n\\s*\\r\\n"); Pattern sentenceEnd = Pattern.compile("[。.!??!]"); for (String para : paragraphs) { para = para.trim(); if (para.isEmpty()) continue; int last = 0; java.util.regex.Matcher matcher = sentenceEnd.matcher(para); while (matcher.find()) { String sentence = para.substring(last, matcher.end()).trim(); if (!sentence.isEmpty()) { sentenceList.add(sentence); } last = matcher.end(); } if (last < para.length()) { String remaining = para.substring(last).trim(); if (!remaining.isEmpty()) { sentenceList.add(remaining); } } } sentences = sentenceList.toArray(new String[0]); Log.d(TAG, "共分割出 " + sentences.length + " 个句子"); } private void highlightInOriginalText(int globalStart, int globalEnd) { Log.d(TAG, "高亮范围: [" + globalStart + ", " + globalEnd + ")"); if (fullOriginalText == null || globalStart >= globalEnd || globalEnd > fullOriginalText.length()) { return; } List<HighlightRange> ranges = findRangesInNodes(globalStart, globalEnd); if (ranges.isEmpty()) { Log.w(TAG, "未找到匹配节点进行高亮"); return; } StringBuilder js = new StringBuilder(); js.append("(function() {"); js.append(" var oldMarks = document.querySelectorAll('mark.highlight');") .append(" oldMarks.forEach(function(m) {") .append(" var p = m.parentNode;") .append(" p.replaceChild(document.createTextNode(m.textContent), m);") .append(" p.normalize();") .append(" });"); for (HighlightRange range : ranges) { String escapedText = escapeJsString(range.node.text.substring(range.startInNode, range.endInNode)); js.append(String.format( "createHighlightAtNodeByText('%s', %d, %d);", escapedText, range.startInNode, range.endInNode )); } js.append(" setTimeout(function(){") .append(" var h = document.querySelector('mark.highlight');") .append(" if(h)h.scrollIntoView({behavior:'smooth',block:'center'});") .append(" }, 50);"); js.append("})();"); mWebView.evaluateJavascript(js.toString(), null); } private List<HighlightRange> findRangesInNodes(int start, int end) { List<HighlightRange> result = new ArrayList<>(); for (NodeInfo node : nodeInfoList) { int ns = node.start; int ne = node.start + node.text.length(); if (end <= ns || start >= ne) continue; int ls = Math.max(0, start - ns); int le = Math.min(node.text.length(), end - ns); if (ls < le) { result.add(new HighlightRange(node, ls, le)); } } return result; } private String escapeJsString(String s) { return s.replace("\\", "\\\\") .replace("'", "\\'") .replace("\"", "\\\"") .replace("\n", "\\n") .replace("\r", "\\r") .replace("\t", "\\t"); } private void speakFromCurrentPosition() { if (sentences == null || currentSentenceIndex >= sentences.length) { stopSpeaking(); return; } String sentence = sentences[currentSentenceIndex].trim(); if (sentence.isEmpty()) { currentSentenceIndex++; handler.postDelayed(this::speakFromCurrentPosition, 50); return; } int pos = fullOriginalText.indexOf(sentence); if (pos == -1) { // 尝试去除空格再找一次 String cleanFull = fullOriginalText.replaceAll("\\s+", ""); String cleanSent = sentence.replaceAll("\\s+", ""); int idx = cleanFull.indexOf(cleanSent); if (idx != -1) { pos = approximateGlobalPosition(idx, cleanSent.length()); } } if (pos == -1) { Log.w(TAG, "无法定位句子: " + sentence); currentSentenceIndex++; handler.postDelayed(this::speakFromCurrentPosition, 50); return; } int highlightStart = pos + currentCharIndex; int highlightEnd = pos + sentence.length(); highlightInOriginalText(highlightStart, highlightEnd); String toSpeak = sentence.substring(currentCharIndex); Bundle params = new Bundle(); String utteranceId = UUID.randomUUID().toString(); params.putCharSequence(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId); int status = tts.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, params, utteranceId); if (status == TextToSpeech.ERROR) { Log.e(TAG, "TTS 播放错误"); } } private int approximateGlobalPosition(int cleanIndex, int cleanLength) { int realPos = 0; int cleanPos = 0; for (int i = 0; i < fullOriginalText.length(); i++) { char c = fullOriginalText.charAt(i); if (!Character.isWhitespace(c)) { if (cleanPos == cleanIndex) { return i; } cleanPos++; } } return -1; } private void setupButtons() { Button speakButton = findViewById(R.id.speakButton); speakButton.setOnClickListener(v -> { if (isPaused && currentSentenceIndex < sentences.length) { isPaused = false; isSpeaking = true; speakFromCurrentPosition(); } else { startSpeaking(); } }); Button pauseButton = findViewById(R.id.pauseButton); pauseButton.setOnClickListener(v -> { if (isSpeaking) { tts.stop(); isSpeaking = false; isPaused = true; } }); Button stopButton = findViewById(R.id.stopButton); stopButton.setOnClickListener(v -> stopSpeaking()); } private void startSpeaking() { if (sentences == null || sentences.length == 0) { Toast.makeText(this, "尚未加载文本内容", Toast.LENGTH_SHORT).show(); return; } isSpeaking = true; isPaused = false; currentCharIndex = 0; speakFromCurrentPosition(); } private void stopSpeaking() { if (tts != null) { tts.stop(); } isSpeaking = false; isPaused = false; currentCharIndex = 0; saveProgress(); removeHighlight(); } private void removeHighlight() { mWebView.evaluateJavascript("(function(){" + "var ms=document.querySelectorAll('mark.highlight');" + "ms.forEach(m=>{m.parentNode.replaceChild(document.createTextNode(m.textContent),m);});" + "})()", null); } private void saveProgress() { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("currentSentenceIndex", currentSentenceIndex); editor.putInt("currentCharIndex", currentCharIndex); editor.apply(); } private void loadProgress() { currentSentenceIndex = sharedPreferences.getInt("currentSentenceIndex", 0); currentCharIndex = sharedPreferences.getInt("currentCharIndex", 0); } private void initTextToSpeech() { tts = new TextToSpeech(this, status -> { if (status == TextToSpeech.SUCCESS) { isTTSInitialized = true; setUtteranceProgressListener(); } else { Toast.makeText(this, "TTS初始化失败", Toast.LENGTH_SHORT).show(); } }); } private void setUtteranceProgressListener() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { tts.setOnUtteranceProgressListener(new UtteranceProgressListener() { @Override public void onStart(String utteranceId) {} @Override public void onDone(String utteranceId) { handler.post(() -> { currentSentenceIndex++; currentCharIndex = 0; if (currentSentenceIndex < sentences.length) { speakFromCurrentPosition(); } else { isSpeaking = false; saveProgress(); Toast.makeText(MainActivity.this, "朗读完成", Toast.LENGTH_SHORT).show(); } }); } @Override public void onError(String utteranceId) {} }); } } @Override protected void onDestroy() { if (tts != null) { tts.stop(); tts.shutdown(); } super.onDestroy(); } // --- 数据类 --- public static class NodeInfo { String text; int start; NodeInfo(String text, int start) { this.text = text; this.start = start; } } public static class HighlightRange { NodeInfo node; int startInNode, endInNode; HighlightRange(NodeInfo node, int start, int end) { this.node = node; this.startInNode = start; this.endInNode = end; } } // --- JS 接口 --- public class TextNodeInterface { @JavascriptInterface public void onTextNodesCollected(String fullText, String nodeInfoJson) { runOnUiThread(() -> { if (fullText == null || fullText.trim().isEmpty()) { Toast.makeText(MainActivity.this, "未提取到有效文本", Toast.LENGTH_SHORT).show(); return; } fullOriginalText = fullText; nodeInfoList.clear(); try { JSONArray arr = new JSONArray(nodeInfoJson); for (int i = 0; i < arr.length(); i++) { JSONObject obj = arr.getJSONObject(i); String text = obj.getString("text"); int start = obj.getInt("start"); nodeInfoList.add(new NodeInfo(text, start)); } Log.d(TAG, "✅ 成功解析 " + nodeInfoList.size() + " 个文本节点"); } catch (Exception e) { Log.e(TAG, "解析 nodeInfo 失败", e); Toast.makeText(MainActivity.this, "结构解析失败", Toast.LENGTH_SHORT).show(); return; } splitSentences(fullOriginalText); }); } } private void loadWebContent(String url) { mWebView.loadUrl(url); } @Override public void onBackPressed() { if (mWebView.canGoBack()) { mWebView.goBack(); } else { super.onBackPressed(); } }} 这是你修改的java代码 还有个名为:collect_text_nodes.js的代码如何 :// collect_text_nodes.js (function() { var textNodes = []; var fullText = ''; function traverse(node) { if (node.nodeType === Node.TEXT_NODE) { var text = node.textContent; if (text && text.length > 0) { textNodes.push({ text: text, start: fullText.length }); fullText += text; } } else if (node.nodeType === Node.ELEMENT_NODE) { var tag = node.tagName.toLowerCase(); if (tag !== 'script' && tag !== 'style' && tag !== 'noscript') { for (var i = 0; i < node.childNodes.length; i++) { traverse(node.childNodes[i]); } } } } var container = document.getElementById('content') || document.querySelector('.content') || document.body; traverse(container); var iframes = document.getElementsByTagName('iframe'); for (var i = 0; i < iframes.length; i++) { try { var iframeDoc = iframes[i].contentDocument || iframes[i].contentWindow.document; if (iframeDoc) { traverse(iframeDoc.body); } } catch (e) { console.log("跨域iframe不可访问: " + e.message); } } try { if (typeof window.TextNodeInterface !== 'undefined') { window.TextNodeInterface.onTextNodesCollected(fullText, JSON.stringify(textNodes)); } else { console.error("❌ 未注册 TextNodeInterface,请检查 addJavascriptInterface"); } } catch (e) { console.error("❌ 回传数据失败: ", e); } console.log("✅ collect_text_nodes.js 已执行,找到文本节点数:", textNodes.length); })();
最新发布
10-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值