【问题标题】:HTML image 'onclick' redirects to another page when calling javascript function (unwanted)调用 javascript 函数时,HTML 图像“onclick”重定向到另一个页面(不需要)
【发布时间】:2016-01-24 13:30:39
【问题描述】:

我有一个要单击的 HTML 图像,它将触发一个要调用的 javascript 函数,该函数将根据 ruby​​ 生成的collection_select 对页面进行一些更改。但每当我尝试调用该函数时,它重定向到另一个页面 (pages\main.html.erb),这不是我想要的。

html图片(及相关代码):

<%= f.collection_select :id,
    Customer.where(business_id: current_customer.business_id),
    :id,
    :full_name,
     { prompt: 'Select' },
     { id: "colleage-select", onChange: "renderColCal(this)" } %>

<input type="image" src="http://..." onclick="addParticipant()">

 ....

<p>Meeting Participants:</p>
 <ol id ="list">

 </ol>

javascript:

//application.js

var List = document.getElementById('list'); //found in events\new.html.erb

function addParticipant(){

    var name = document.getElementById('colleague-select').textContent; //gets :full_name of selected Customer
    var entry = document.createElement('li'); //creates new list element within ordered list 'list'
    entry.appendChild(document.createTextNode(name)); //adds :full_name to list element
    List.appendChild(entry); //adds list element to ordered list

}

我已将'addParticipant()' 中的代码替换为alert('hello'),并且在没有重定向的情况下运行良好,那么我的javascript 代码中是什么导致了问题?任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 尝试在src中添加“#”
  • 你的意思是把它加到开头吗?我试过了,它仍然重定向..
  • 抱歉, "addParticipant()" %> 试试这个 rails 链接
  • rubymine 出于某种原因不喜欢这种语法,它在 :onclick 周围突出显示“期望 %>、; 或
  • 你确定:onclick前面有逗号吗?

标签: javascript html ruby-on-rails ruby


【解决方案1】:

弹出的警告对话框会停止默认点击行为,但您的代码不会。

您需要明确地这样做:

function addParticipant(e) {
  ...
  e.preventDefault();
}

【讨论】:

  • 您能想到这仍然会发生的任何其他原因吗?我很困惑它如何知道要发送到哪个页面以及如何获取其地址
  • renderColCal(this) 里面有什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 1970-01-01
相关资源
最近更新 更多