将 javascript onclick 事件更改为 jquery click 并仍然传递参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3631403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change javascript onclick event to jquery click and still pass parameters
提问by Cydaps
I think I may be missing something or haven't grasped a fundamental of jQuery. I have searched for hours but yet to find an answer to my question.
我想我可能遗漏了一些东西或者没有掌握 jQuery 的基础知识。我已经搜索了几个小时,但还没有找到我的问题的答案。
I've got an old website that I'm upgrading to use jQuery and many of the links call a JavaScript onClickcall that passes multiple parameters, as per the example below:
我有一个旧网站,我正在升级以使用 jQuery,并且许多链接调用onClick传递多个参数的 JavaScript调用,如下例所示:
<a href="#" onclick="displayData('Book Title', 'ISBN', 'dateOfPublishing', 'Price');">View Details</a>
The problem is that I've updated the old displayDatafunction with various jQuery code and the displayDatafunction is within the
问题是我已经displayData用各种 jQuery 代码更新了旧函数,并且该displayData函数在
$(document).ready(function() {
});
code, and this seems to prevent the function displayDatabeing called using the onClickas it says object expected. I've moved the displayDatafunction out from the $(document).ready()but by doing so, this has prevented references to other functions within the $(document).ready()code being referenced.
代码,这似乎阻止了函数displayData被调用,onClick因为它说的是object expected。我已将displayData函数从 中移出,$(document).ready()但这样做阻止了对$(document).ready()所引用代码中其他函数的引用。
A cut down example of what I have is below:
我所拥有的简化示例如下:
<script>
$(document).ready(function() {
function displayData(title, isbn, dt, price) {
// there's a call to jQuery AJAX here
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebServices/BookService.asmx/GetBookReviews",
data: "{isbn: '" + isbn + "'}",
dataType: "json",
success: function(msg) {
DisplayReviews(msg.d);
}
});
return false;
}
function DisplayReviews(data) {
// data normally formatted here and passed to formattedData variable
var formattedData = FormatData(data);
$('#reviewScreen').html(formattedData);
}
function FormatData(data) {
// function reformats data... code removed for space..
return data;
}
});
</script>
<table>
<tr><td><a href="#" class="reviewLink" onclick="displayData('Book Title', '1234141HABJA1', '2010-01-12', '.99');">View Reviews</a></td><td>Book Title</td></tr>
<tr><td><a href="#" class="reviewLink" onclick="displayData('Book TItle 2', '516AHGN1515', '1999-05-08', '.00');">View Reviews</a></td><td>Book Title 2</td></tr>
</table>
What I'd like to do is to be able to remove the onclick="displayData();"within the link and instead us a jQuery click reference, something like
我想要做的是能够删除onclick="displayData();"链接内的 ,而不是我们一个 jQuery 单击引用,例如
$('a.reviewLink').click(function() {
displayData(parameters go here....);
});
I just don't know how I'd pass the parameters to the function from the link as they would not longer be in the HTML onclickattribute.
我只是不知道如何将参数从链接传递给函数,因为它们不再存在于 HTMLonclick属性中。
If I continue to use the onclickattribute in the link, and move the displayData(params)out of the $(document).ready()code block, it works fine, but the moment I try and reference any of the other functions within the $(document).ready()code block I get the dreaded object expectederror with the other functions such as DisplayReviews(param).
如果我继续使用onclick链接中的属性,并将其displayData(params)移出$(document).ready()代码块,它可以正常工作,但是当我尝试引用$(document).ready()代码块中的任何其他函数时,我会得到可怕的对象预期错误等功能DisplayReviews(param)。
I don't know if this makes any sense.... sorry if it's confusing, I'm not the worlds best programmer and don't know all the terminology necessarily, so have tried as best I can to explain. I hope you can help.
我不知道这是否有意义......如果它令人困惑,抱歉,我不是世界上最好的程序员,也不一定了解所有术语,所以尽我所能来解释。我希望你能帮忙。
Many thanks
非常感谢
回答by BGerrissen
The init code should go into the .ready(), not your library functions, those can be defined in a seperate .js file.
init 代码应该进入 .ready(),而不是你的库函数,那些可以在单独的 .js 文件中定义。
<script src="yourFunctions.js"></script>
<script>
$(document).ready(function(){
$('a.reviewLink').click(function() {
displayData(parameters go here....); // in yourFunctions.js
});
});
</script>
An alternative to passing inline parameters without using inline javascript, is to use HTML5's 'data-' attribute on tags. You can use it in xhtml, html etc as well and it just works.
在不使用内联 javascript 的情况下传递内联参数的另一种方法是在标签上使用 HTML5 的“data-”属性。您也可以在 xhtml、html 等中使用它,并且它可以正常工作。
html:
html:
<div data-name="Hyman" data-lastname="black">My name is</div>
jquery:
查询:
$('div').click(function(){
alert($(this).attr('data-name') + ' ' + $(this).attr('data-lastname'));
});
Note: You HAVE to use either jQuery's .attr()or native .getAttribute()method to retreive 'data-' values.
注意:您必须使用 jQuery.attr()或本机.getAttribute()方法来检索 'data-' 值。
I use 'data-' myself all the time.
我自己一直使用“数据-”。
回答by Ender
As pointed out by Skilldrick, displayDatadoesn't need to be defined inside your document ready wrapper (and probably shouldn't be).
正如 Skilldrick 所指出的,displayData不需要在您的文档就绪包装器中定义(并且可能不应该)。
You are correct in wanting to use the jQuery click event assignment rather than onClick - it makes your code easier to read, and is required by the principle of Unobtrusive Javascript.
您想要使用 jQuery 单击事件分配而不是 onClick 是正确的 - 它使您的代码更易于阅读,并且是 Unobtrusive Javascript 原则所要求的。
As for those parameters that you want to pass, there are a few ways to go about the task. If you are not concerned with XHTML compliance, you could simply put some custom attributes on your link and then access them from your script. For example:
至于你想传递的那些参数,有几种方法可以完成任务。如果您不关心 XHTML 合规性,您可以简单地将一些自定义属性放在您的链接上,然后从您的脚本中访问它们。例如:
<a href="#" booktitle="Book Title" isbn="ISBN" pubdate="Publish Date" price="Price">View Details</a>
And then in your click event:
然后在您的点击事件中:
$('a.reviewLink').click(function() {
var booktitle = $(this).attr('booktitle');
var isbn = $(this).attr('isbn');
var pubdate = $(this).attr('pubdate');
var price = $(this).attr('price');
displayData(booktitle, isbn, pubdate, price);
});
I'm sure someone on here will decry that method as the darkest evil, but it has worked well for me in the past. Alternatively, you could follow each link with a hidden set of data, like so:
我敢肯定这里有人会谴责这种方法是最黑暗的邪恶,但它在过去对我来说效果很好。或者,您可以使用一组隐藏的数据跟踪每个链接,如下所示:
<a href="#">View Details</a>
<ul class="book-data">
<li class="book-title">Book Title</li>
<li class="book-isbn">ISBN</li>
<li class="book-pubdate">Publish Date</li>
<li class="book-price">Price</li>
</ul>
Create a CSS rule to hide the data list: .book-data { display: none; }, and then in your click event:
创建一个 CSS 规则来隐藏数据列表:.book-data { display: none; },然后在您的点击事件中:
$('a.reviewLink').click(function() {
var $bookData = $(this).next('.book-data');
var booktitle = $bookData.children('.book-title').text();
var isbn = $bookData.children('.book-isbn').text();
var pubdate = $bookData.children('.book-pubdate').text();
var price = $bookData.children('.book-price').text();
displayData(booktitle, isbn, pubdate, price);
});
There are lots of ways to accomplish your task, but those are the two that spring most quickly to mind.
有很多方法可以完成您的任务,但最容易想到的就是这两种。
回答by Sandro
I worked this up, so even though the question is answered, someone else might find it helpful. http://jsbin.com/axidu3
我解决了这个问题,所以即使问题得到了回答,其他人也可能会觉得它有帮助。 http://jsbin.com/axidu3
HTML
HTML
<table border="0" cellspacing="5" cellpadding="5">
<tr>
<td>
<a href="#" class="reviewLink">View Reviews</a>
<div class="displayData">
<span class="title">Book Title 2</span>
<span class="isbn">516AHGN1515</span>
<span class="pubdata">1999-05-08</span>
<span class="price">.00</span>
</div>
</td>
<td>Book Title 2</td>
</tr>
</table>
JavaScript
JavaScript
<script type="text/javascript" charset="utf-8">
jQuery(".reviewLink").click(function() {
var title = jQuery(".title", this.parent).text();
var isbn = jQuery(".isbn", this.parent).text();
var pubdata = jQuery(".pubdata", this.parent).text();
var price = jQuery(".price", this.parent).text();
displayData(title, isbn, pubdata, price);
});
function displayData(title, isbn, pubdata, price) {
alert(title +" "+ isbn +" "+ pubdata +" "+ price);
}
</script>
CSS
CSS
<style type="text/css" media="screen">
.displayData {
display: none;
}
</style>

