我有一个 HTML 按钮:
<button>
<img id = "click-me" src="https:..." alt="Add to List" style="width: 50px"/>
</button>
点击时,应执行此 JQuery 代码:
$(function () {
$("#click-me").click(function () {
document.getElementById('list').style.backgroundColor = "red";
});
});
但是,点击按钮并没有按照我的意愿去做,而是将我带到了我网站的另一个页面。我该如何阻止呢?谢谢
编辑:
这是页面的完整 html:
<div class="form">
<h1>Create A Meeting</h1>
<%= form_for(@newevent) do |f| %>
<%= f.text_field :name, :placeholder => "Title" %>
<!--< f.collection_select :location, Location.all, :id, :locName %> FOR WHEN LOCATIONS ARE A THING-->
<%= f.text_field :description, :placeholder => "Short Description" %>
<div>
<h2>Who's involved?</h2>
<p>select a colleague to compare their calendar with yours</p>
<%= f.collection_select :id,
Customer.where(business_id: current_customer.business_id),
:id,
:full_name,
{ prompt: 'Select' },
{ id: "colleage-select", onChange: "renderColCal(this)" } %>
<button id="click-me" type="button">
<img src="https://cdn4.iconfinder.com/data/icons/basic-ui-elements/700/07_plus-128.png" alt="Add to Event" style="width: 50px"/>
</button>
<div class = 'row'>
<div class = 'col-md-6' id = 'left-calendar-wrapper'>
<h3>Your calendar:</h3>
<%= render partial: '/calendars/show', locals: {} %>
</div>
<div class="col-md-6" id="calendar-wrapper">
<h3>Your colleague's calendar:</h3>
</div>
<div>
<p>Meeting Participants:</p>
<ol id ="list">
<li>list</li>
</ol>
</div>
</div>
</div>
<div>
<h2>when do you want it to start?</h2>
<%= f.datetime_select :starts_at, :placeholder => "when do you want it?" %>
</div>
<div>
<h2>when do you want it to end?</h2>
<%= f.datetime_select :ends_at, :placeholder => "when should it end?" %>
</div>
<%= f.submit "Create Meeting", class: "btn-submit" %>
<% end %>
</div>
</div>
</div>
JQuery 保持不变
最佳答案
将 id="click-me"
添加到 button
而不是 img
。另外,请为 button
添加 type="button"
。
添加 e.preventDefault()
或 return false
:
$(function () {
$("#click-me").click(function () {
document.getElementById('list').style.backgroundColor = "red";
return false;
});
});
或者:
$(function () {
$("#click-me").click(function (e) {
e.preventDefault();
document.getElementById('list').style.backgroundColor = "red";
});
});
关于javascript - 如何停止自动重定向到另一个网页的html按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34980449/