编辑:这是表格中的全部内容
希望这会有所帮助,现在之前适用于警报的代码不再适用。这与它在表格中有关吗?
示例:http://jsfiddle.net/fT8aL/13/
<小时/>我有一个网络应用程序,我正在尝试对其进行一些修改。无论如何,当我单击链接时,我希望它调用发送电子邮件的函数。第一项是页面上的文本,第二项是调用用户名的变量。
在 .jsp 文件中,我修改以下行:
<a href="${videoUrl}" target="main" onclick="sendMail(this.parentNode.getElementsByTagName('span')[2].attributes['title'].value, '${model.user.username}')">
上面的代码在使用警报而不是 sendMail 函数进行测试时有效。您可以在这里查看:http://jsfiddle.net/rr6Wk/72/
我的问题是它没有发送电子邮件,我猜我的格式或上面的代码有一些错误。
有什么想法吗?
功能:
<script>
function sendMail(video, user) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {// IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://www.yourdomain.com/somedirectory/sendemail.php?video="+video+"&user="+user+'&ip=<%= request.getHeader("X-Real-IP") %>', false);
xmlhttp.send();
}
</script>
这可以工作,但不可用,因为所有项目都有好的名称 ID:
<a href="${videoUrl}" target="main" onclick="sendMail(document.getElementById('nicename').title, '${model.user.username}')">
在另一个名为 main.jsp 的文件中,我添加了 id="nicename"但是这不起作用,因为如果我单击第三个项目,它总是显示第一个项目的好名称:
<td ${class} style="padding-right:1.25em;white-space:nowrap">
<span id="nicename" title="${child.title}"><str:truncateNicely upper="${cutoff}">${fn:escapeXml(child.title)}</str:truncateNicely></span>
</td>
最佳答案
如果存在多个具有相同 ID 的元素,
getElementById
将始终返回第一个元素。因此,它不适用于该目的。为每个nicename使用不同的ID,或者使用name
(而不是ID)属性和getElementsByName
。
对于 getElementsByName
示例:
<script>
function doSendMail(videoIndex, userName) {
//get the list of nicename elements
var eles = document.getElementsByName('nicename');
//send the mail. note: error handling is absent
sendMail(eles[videoIndex].title, userName);
}
</script>
<!--send mail for the 3rd video-->
<a href="${videoUrl}" target="main" onclick="doSendMail(2, '${model.user.username}')">
第三个选项是使用基于单击元素的相对元素引用,使用 this
并遍历 HTML 节点来获取所需的元素(标题)。在提供的 jsfiddle 中,该表有 7 列。要单击的元素位于第 2 列(播放链接),所需元素位于第 6 列(SPAN
元素)。此方法不需要 name
和 id
属性。
<script>
function doSendMail(playLinkEle, user) {
var row = playLinkEle.parentNode.parentNode; //get cell, then row
var cell = row.cells[5]; //get 6th cell (same row)
var ele = cell.firstElementChild; //get first child element
sendMail(ele.title, user);
}
</script>
<table>
<tr>
<td>
star image
</td>
<td>
<a onclick="doSendMail(this, '${model.user.username}')" target="main" href="${videoUrl}">play link</a>
</td>
<td>
empty column
</td>
<td>
download link
</td>
<td>
song id
</td>
<td>
unknown detail
</td>
<td>
<span title="The Title">The Title</span>
</td>
<td>
duration detail
</td>
</tr>
</table>
duration detail
关于OnClick 函数的 Javascript 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12920173/