如何使用jQuery替代innerHTML?需重构原生JS代码以符合安全规范
Convert Vanilla JS Message Creator to jQuery (Secure & Clean)
Got it! Let's convert your vanilla JavaScript code to jQuery while fixing security risks (like unsafe HTML string concatenation) and sticking to clean, separate JS/HTML practices. Here's a proper implementation that avoids messy HTML strings and uses jQuery's safe DOM manipulation methods:
var demoName1 = "Peter Stone"; function showMessage() { // Safely get input value (trim to avoid empty messages) var inputText = $('#inputText').val().trim(); if (!inputText) return; // Exit early if input is empty // 1. Create main message container var messageBox = $('<div>', { id: 'messageBoxSend' }); // 2. Add name section $('<div>', { class: 'nameSend', text: demoName1 }).appendTo(messageBox); // 3. Add text wrapper and inner empty div var textWrapper = $('<div>', { class: 'text' }).appendTo(messageBox); $('<div>', { id: 'FscToolPaneNoseSend' }).appendTo(textWrapper); // 4. Add input text (automatically escaped to prevent XSS) textWrapper.append(document.createTextNode(inputText)); // 5. Format and add timestamp var now = new Date(); var hours = now.getHours(); var minutes = now.getMinutes(); var formattedTime = `${hours}:${minutes < 10 ? '0' + minutes : minutes}`; $('<div>', { class: 'time', text: formattedTime }).appendTo(messageBox); // 6. Add line break (match original behavior) var lineBreak = $('<br>'); // Append everything to your target container (replace with your actual target ID/class) $('#yourChatContainer').append(messageBox, lineBreak); // Optional: Clear input after sending $('#inputText').val(''); }
Key Improvements & Explanations:
- Security First: No more HTML string concatenation! jQuery's element creation syntax (
$('<div>', { ... })) anddocument.createTextNode()automatically escape special characters, eliminating XSS risks from user input. - Clean Structure: We build each component of the message box step-by-step, appending them to their parent elements instead of gluing strings together. This makes the code easier to read and modify.
- Separation of Concerns: All DOM manipulation lives in JS, no inline HTML mixed in—perfect for your requirement.
- Identical Logic: The timestamp formatting matches your original code exactly, just written more concisely with a ternary operator and template literal.
- Input Sanity Check: Added a quick check to skip empty messages (you can remove this if you want to allow empty sends).
Just replace #yourChatContainer with the actual ID/class of the element where you want to append the message, and you're good to go!
内容的提问来源于stack exchange,提问作者candy fan
相关产品推荐
相关产品推荐

