简体   繁体   English

如何使用href和onclick函数传递参数

[英]How to pass parameter with a href and onclick function

I want to pass parameter when I click in <a href> , first I have this and works fine: 我想点击<a href>时传递参数,首先我有这个并且工作正常:

    <a href="#" rel="like{{num}}"> I like </a>|

   $("a[rel^='like']").click(function(){
            $.ajax({
                ...
            });

but I don't know how to pass parameter to that function, so I do this: 但我不知道如何将参数传递给该函数,所以我这样做:

    <a href="#" rel="like{{num}}"
          onclick="cap(para1, para2)"> I like </a>

Finally, in my Javascript I have this simple function: 最后,在我的Javascript中我有这个简单的功能:

    function cap(para1, para2){
        alert('here');
    }

but I obtain this error: 但是我得到了这个错误:

ReferenceError: cap is not defined

Any idea? 任何想法?

A solution is to use data attributes : 解决方案是使用数据属性

<a href="#" rel="like{{num}}" data-para1="Oh"  data-para2="{{somepara}}"> I like </a>

<script>
function cap(para1, para2){
    alert('here');
}
$("a[rel^='like']").click(function(){
   var para1 = this.dataset['para1'];
   var para2 = this.dataset['para2'];
   cap(para1, para2);
});
</script>

You may also write it like this if you prefer a more structured approach : 如果您更喜欢更结构化的方法,您也可以这样写:

<a href="#" rel="like{{num}}" data-params="{'para1':'Oh','para2':'{{somepara}}'}"> I like </a>

$("a[rel^='like']").click(function(){
   var params = this.dataset['params'];
   var para1 = params.para1;
   var para2 = params.para2;

Note that if the document isn't an HTML5 document you'll have to use the more compatible data function of jQuery (but there hardly is any reason not to use HTML5 doctype today) : 请注意,如果文档不是HTML5文档,则必须使用jQuery的更兼容的数据功能 (但是现在几乎没有理由不使用HTML5 doctype):

var para1 = this.data('para1');

You may like to try this. 你可能想尝试这个。

<a class="ilike" href="javascript:;" data-p1="abc" data-p2="123"> I like </a>

<script>
    function cap(para1, para2){
        alert('here');
    }

    $(function(){
        $('.ilike').click(function(){
            var $this = $(this);
            var p1 = $this.data('p1');
            var p2 = $this.data('p2');
            cap(p1, p2);
        });
    });

</script>

If you want to do it via onclick, it's either that 1) you have declared your function in wrong scope or 2) another JS error occurred before the function declaration and caused it to not be executed. 如果你想通过onclick来做,那就是1)你已经在错误的范围内声明你的函数或2)在函数声明之前发生了另一个JS错误并导致它不被执行。

To fix the scope problem, you can try doing window.cap = function(para1, para2) { ... 要解决范围问题,你可以尝试做window.cap = function(para1, para2) { ...

To see if there are any errors, try something like firebug or any browser developer tools and check for errors under console. 要查看是否存在任何错误,请尝试使用firebug或任何浏览器开发人员工具,并检查控制台下的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM