如何将EventSource更新的panic_status元素内容存入其他脚本变量?
panic_status Element's Content into a Variable Got it, let's break this down simply. The key thing to note here is that .value is meant for form elements like <input> or <textarea>—but your original script uses innerHTML to update the panic_status element, which means it's probably a non-form element like a <div>, <span>, or <p>.
To grab its content into a variable, you have two straightforward options depending on what you need:
Option 1: Get the full HTML content
If the event.data from your EventSource includes HTML tags and you want to preserve that structure, use innerHTML:
var panicContent = document.getElementById("panic_status").innerHTML;
Option 2: Get plain text only
If you just need the raw text (stripping any HTML tags that might be present), use textContent instead:
var panicText = document.getElementById("panic_status").textContent;
Quick Pro Tip
Make sure this code runs after the EventSource has updated the panic_status element. If you need to capture the value every time it changes, you could even extend your original EventSource handler to store the value directly, like this:
var currentPanicStatus; // Declare a variable outside the handler to keep track var source = new EventSource("panic.php"); source.onmessage = function(event) { document.getElementById("panic_status").innerHTML = event.data; currentPanicStatus = event.data; // Store the value directly here };
This way, you can access currentPanicStatus from your other script whenever you need it, without having to read the element's content later.
内容的提问来源于stack exchange,提问作者RUHAIZAN FAZREEN ASHRAFF MOHD

