繁体   English   中英

使用JavaScript更改跨度内容

[英]Change span content using javascript

它是这样工作的:当我单击订阅按钮时,它显示一条消息:

<span id="es_msg">
Your subscription was successful! Kindly check your mailbox and confirm your subscription. If you don't see the email within a few minutes, check the spam/junk folder.</span>

而且我必须使用javascript更改此消息,因为我无权访问html。 我尝试使用下面的代码,但是即使单击订阅按钮之前,“测试”消息也始终可见。

document.getElementById('es_widget_msg').innerHTML='Test';

那是因为您没有将代码设置为“事件处理程序”的一部分 一旦遇到它,它就在没有任何用户参与的情况下运行。 您说自己想单击span时更改文本。

 // Get a reference to the span let span = document.getElementById("es_msg"); // Set up a click event that references the correct event handling function span.addEventListener("click", doClick); // Define the handler function function doClick(){ // In the DOM handler, the element that caused the event // is available via the keyword "this". Also, if you are not // modifying the HTML content of an element, use .textContent // not .innerHTML this.textContent = 'Test'; } 
 <span id="es_msg"> Your subscription was successful! Kindly check your mailbox and confirm your subscription. If you don't see the email within a few minutes, check the spam/junk folder.</span> 

您尝试下面的jQuery代码。

$('body').on('click', '#subscribeId', function() {
    $('body').find('#es_msg').text('Test');
});

如果您在执行此操作时未使用事件处理机制,则添加的代码将在页面加载时起作用,并且比您预期的要早得多地将消息重写为“测试”。 因此,您必须添加处理程序。 在这里,我们使用订阅按钮ID或类名来处理对订阅按钮的单击。 在这种情况下,仅当事件发生时才执行操作。 您的点击按钮。

希望这对您有帮助。

您可以将msg存储在元素的data-*属性中。

 var $el_btn = $("#es_txt_button"); var $el_msg = $("#es_msg"); $el_btn.on("click", function(e) { e.preventDefault(); // submit to backend and on succes do: $el_msg.text($el_msg.data("msg")); }) 
 <button id="es_txt_button">Subscribe</button> <span id="es_msg" data-msg="Your subscription was successful!"></span> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

或用普通的JS

 const el_btn = document.querySelector("#es_txt_button"); const el_msg = document.querySelector("#es_msg"); const subscribe = (e) => { e.preventDefault(); // submit to backend and on succes do: el_msg.textContent = el_msg.getAttribute("data-msg"); }; el_btn.addEventListener("click", subscribe); 
 <button id="es_txt_button">Subscribe</button> <span id="es_msg" data-msg="Your subscription was successful!"></span> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM