【问题标题】:I cant use the function argument in my code我不能在我的代码中使用函数参数
【发布时间】:2021-03-01 02:27:09
【问题描述】:

我的 javascript 代码是

    $(document).ready(function today(tony){
    var mytext = tony;
    $('#tod').click(function(event){

    event.preventDefault();

$.ajax({
    url:"/ajaxdemo",
    data:{text:mytext},
    method:"POST",
    success: function(res){
        alert(res.from)
    },
    error: function(err){
        console.log(err)
    }

})

}) })

我的html代码是

<a id="tod" href="" onclick="today(tony)" ><i class="fa fa-calendar"></i>{{this.tod}}</a>

我不能接受名为 today(tony) 的函数中的参数

【问题讨论】:

  • 您是否希望在文档准备好或有人单击链接时调用 function today?还是两者兼而有之?
  • 当今天有人想要点击链接功能时
  • 然后您希望该函数在#tod 上设置另一个点击处理程序?
  • 顺便说一句,您希望tonytoday(tony) 中引用什么?
  • 这只是我试过实际上我想要那个日期{{this.tod}}

标签: javascript function arguments


【解决方案1】:

这个怎么样:

const some_func = (mytext) => 
{
   event.preventDefault()

    $.ajax({
        url:"/ajaxdemo",
        data:{text:mytext},
        method:"POST",
        success: (res) => alert(res.from),
        error: (err) => console.log(err)
    })
}

const today = (tony) => $('#tod').click(() => some_func(tony))

$(document).ready(today)

【讨论】:

  • 我们如何在您的代码中添加 event.preventDefault()
  • 在控制台中显示 tony 未定义
【解决方案2】:

我找到了解决办法

将javascript代码更改为

function today(tod) {
$.ajax({
    url: "/ajaxdemo",
    data: {
        text: tod
    },
    method: "POST",
    success: function (res) {
        alert(res.from)
    },
    error: function (err) {
        console.log(err)
    }

});
return false;
}

将 HTML 代码更改为

<a id="tod" href="" onclick="today(tony)" ><i class="fa fa-calendar"></i>{{this.tod}}</a>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    • 2017-02-18
    • 2023-03-15
    相关资源
    最近更新 更多