te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>Change javascript onclick event to jquery click and still pass parameters - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Change javascript onclick event to jquery click and still pass parameters - Stack Overflow

programmeradmin3浏览0评论

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.

I've got an old website that I'm upgrading to use jQuery and many of the links call a JavaScript onClick call that passes multiple parameters, as per the example below:

<a href="#" onclick="displayData('Book Title', 'ISBN', 'dateOfPublishing', 'Price');">View Details</a>

The problem is that I've updated the old displayData function with various jQuery code and the displayData function is within the

$(document).ready(function() { 
});

code, and this seems to prevent the function displayData being called using the onClick as it says object expected. I've moved the displayData function out from the $(document).ready() but by doing so, this has prevented references to other functions within the $(document).ready() code being referenced.

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', '$15.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', '$25.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

$('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 onclick attribute.

If I continue to use the onclick attribute 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 expected error with the other functions such as 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

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.

I've got an old website that I'm upgrading to use jQuery and many of the links call a JavaScript onClick call that passes multiple parameters, as per the example below:

<a href="#" onclick="displayData('Book Title', 'ISBN', 'dateOfPublishing', 'Price');">View Details</a>

The problem is that I've updated the old displayData function with various jQuery code and the displayData function is within the

$(document).ready(function() { 
});

code, and this seems to prevent the function displayData being called using the onClick as it says object expected. I've moved the displayData function out from the $(document).ready() but by doing so, this has prevented references to other functions within the $(document).ready() code being referenced.

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', '$15.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', '$25.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

$('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 onclick attribute.

If I continue to use the onclick attribute 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 expected error with the other functions such as 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

Share Improve this question edited Sep 2, 2010 at 21:35 Felix Kling 817k180 gold badges1.1k silver badges1.2k bronze badges asked Sep 2, 2010 at 21:24 CydapsCydaps 1671 gold badge3 silver badges11 bronze badges 4
  • can you modify the HTML or do you need to extract the parameters from the existing onclick attribute? – Anurag Commented Sep 2, 2010 at 21:28
  • I can modify the HTML, I just wasn't sure whether to stick with the existing onclick or try and better utilize jQuery and extract the parameters some other way. The HTML is dynamically generated so the parameters necessary are appended at this time, hence why i used to used the onclick attribute. Thanks! – Cydaps Commented Sep 2, 2010 at 21:38
  • You could create the necessary JavaScript (namely attaching the click handler) also dynamically. – Felix Kling Commented Sep 2, 2010 at 21:46
  • @Felix: I'll have a look at attaching the click handler dynamically, but do like the idea of the HTML5 BGerrissen refers to. – Cydaps Commented Sep 2, 2010 at 21:51
Add a ment  | 

3 Answers 3

Reset to default 8

The init code should go into the .ready(), not your library functions, those can be defined in a seperate .js file.

<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.

html:

<div data-name="Jack" 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.

I use 'data-' myself all the time.

As pointed out by Skilldrick, displayData doesn't need to be defined inside your document ready wrapper (and probably shouldn't be).

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.

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 pliance, you could simply put some custom attributes on your link and then access them from your script. For example:

<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:

$('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 acplish your task, but those are the two that spring most quickly to mind.

I worked this up, so even though the question is answered, someone else might find it helpful. http://jsbin./axidu3

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">$25.00</span>
            </div>
            </td>
        <td>Book Title 2</td>
    </tr>
</table>

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

<style type="text/css" media="screen">
    .displayData {
        display: none;
    }
</style>
发布评论

评论列表(0)

  1. 暂无评论