简体   繁体   English

如何在innerHTML onclick事件中动态传递字符串参数

[英]How to pass string parameters dynamically in innerHTML onclick event

I am trying to parse a date parameter in a function name select_day. 我正在尝试在函数名称select_day中解析日期参数。 That function is declared in for a li element onclick event. 该函数在li元素onclick事件中声明。 with the below code I am getting this error: 与下面的代码,我得到这个错误:

Uncaught SyntaxError: missing ) after argument list 参数列表后未捕获到的SyntaxError:缺少)

it's actually a date that I am trying to pass. 这实际上是我要通过的日期。 I have tried hard coding the parameter, its working but dynamically it's not working 我尝试对参数进行硬编码,它可以正常工作,但动态地它却无法工作

if(selected_day == dates[i]){
             $(".dates_list").append( "<li class='active' onclick=\'select_day("+$.datepicker.formatDate( "dd M", dates[i])+")\'><span>Day "+day_count+"</span><p>"+$.datepicker.formatDate( "dd M", dates[i]) +"</p></li>" );
        }

I want that function to be executed. 我希望执行该功能。 Could anyone help please 有人可以帮忙吗

Use an .on('click' handler instead of trying to concatenate the Javascript code to be executed into an onclick inline handler: 使用.on('click'处理程序,而不是尝试将要执行的Javascript代码连接到onclick内联处理程序中:

if(selected_day == dates[i]){
  const $li = $(`<li class="active"><span>Day ${day_count}</span><p>${$.datepicker.formatDate( "dd M", dates[i])}</p></li>`);
  $li.on('click', () => {
    select_day($.datepicker.formatDate("dd M", dates[i]));
  });
  $(".dates_list").append($li);
}

Or, more concisely: 或者,更简洁地说:

if(selected_day == dates[i]){
  const formattedDate = $.datepicker.formatDate( "dd M", dates[i]);
  $(`<li class="active"><span>Day ${day_count}</span><p>${formattedDate}</p></li>`)
    .on('click', () => {
      select_day(formattedDate, dates[i]);
    })
    .appendTo('.dates_list');
}

Handlers attached with Javascript are generally a lot easier to manage than on- attribute strings. 附加的JavaScript处理程序通常比一个更容易管理的on-属性字符串。

Your problem is the missing of opening and closing quotes. 您的问题是缺少左引号和右引号。

I recommend you event-delegation for doing this as well as to embrace the binding of events rather than putting events directly into the markup. 我建议您使用事件委托进行此操作,并建议您进行事件绑定,而不是将事件直接放入标记中。

Likewise, you can use the data attribute to store the dates. 同样,您可以使用data属性存储日期。 Further, I added the class date-list in order to identify those elements li . 此外,我添加了班级date-list以标识那些元素li

if (selected_day === dates[i]) {
    let html = "<li data-date='" + $.datepicker.formatDate("dd M", dates[i]) + "' class='date-list active'><span>Day " + day_count + "</span><p>" + $.datepicker.formatDate("dd M", dates[i]) + "</p></li>";
    $(".dates_list").append(html);
}

// Place this in somewhere different than the previous code-snippet 
// and execute it after the DOM is totally loaded
$('.dates_list').on("click", ".date-list", function() {
    select_day(this.data("date"));
});

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

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