使用JavaScript更改跨度内容

时间:2018-09-02 16:55:32

标签: javascript jquery html5

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

<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';

3 个答案:

答案 0 :(得分:1)

那是因为您没有将代码设置为"event handler"的一部分。一旦遇到它,它就在没有任何用户参与的情况下运行。您说过自己,您想在单击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>

答案 1 :(得分:0)

您尝试使用以下jQuery代码。

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

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

希望这对您有所帮助。

答案 2 :(得分:0)

您可以将味精存储在元素的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>