在 for 循环内将值传递给函数不起作用

我正在从 json 文件映射货币,并将映射的货币渲染到组件。我有一个像这样的 .php 文件


<div class="currency-switch-container" id="currency_container">

    <span style="font-size:12px;font-weight:bold">All currencies</span>

    <div id="currency-map" style="margin-top:15px"></div>

</div>

我在我的js文件中引用上述组件中的div,如下所示


let currencyMap = jQuery("#currency-map");

当我的 jQuery 文档准备好时,我正在执行以下操作


jQuery(document).ready(function($) {

  $.getJSON('wp-content/themes/mundana/currency/currency.json', function(data) {

    for(let c in data){

      currencyMap.append(`<span onclick="onCurrencyClick(${data[c].abbreviation})"

      class="currency-item">

        <span>

           ${data[c].symbol}

        </span>

        <span>

          ${data[c].currency}

        </span>

      </span>`)

    }

});


}

我的功能是这样的


function onCurrencyClick(val){

  console.log("val",val);

  setCookie("booking_currency", val, 14);

}

这里该功能不起作用。但是,如果我不向该函数传递任何内容,它似乎可以工作,因为我可以在终端中看到日志。


偶然的你
浏览 78回答 3
3回答

长风秋雁

您好,您的表达式 ${data[c].abbreviation} 会将值放入不带字符串引号的函数字符串中,即结果将是&nbsp;onCurrencyClick(abbreviation)&nbsp;而它应该是 < a i=2>. 请使用 onclick="onCurrencyClick("${data[c].abbreviation}")"相反。onCurrencyClick('abbreviation')

慕侠2389804

不要使用内联onclick,而是使用事件委托。这意味着您有一个事件侦听器来处理来自子代和孙代的所有事件。修改是一个非常小的修改,请参见下面的示例。这样做的原因是您将 JavaScript 保存在 JS 文件中。就像现在一样,您遇到了 JS 错误,并且必须在 HTML 中查找它。这可能会变得非常混乱。然而内联 onclick 监听器也是有效的,但它们已经过时了,应该避免,除非绝对没有其他方法。与 CSS 中使用 !important 进行比较,效果相同。function onCurrencyClick(event){&nbsp; var val = $(this).val();&nbsp; setCookie("booking_currency", val, 14);}currencyMap.on('click', '.currency-item', onCurrencyClick);此示例采用您尝试从单击的 的 属性插入的 val。 元素没有这样的属性,但是 有这样的属性,并且是一个更适合它期望与之交互的元素。将可点击元素用于点击等目的通常是一个很好的做法。 value.current-item<span><button>在下面的示例中,您会看到正在使用的按钮以及在 属性中输出的 abbreviation 值3> 元素,可以从 函数中读取。value<button>onCurrencyClickjQuery(document).ready(function($) {&nbsp; $.getJSON('wp-content/themes/mundana/currency/currency.json', function(data) {&nbsp; &nbsp; for(let c in data){&nbsp; &nbsp; &nbsp; currencyMap.append(`&nbsp; &nbsp; &nbsp; &nbsp; <button value="${data[c].abbreviation}" class="currency-item">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ${data[c].symbol}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ${data[c].currency}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </span>&nbsp; &nbsp; &nbsp; &nbsp; </button>&nbsp; &nbsp; &nbsp; `)&nbsp; &nbsp; }});

函数式编程

onclick不适用于动态添加的 div 标签你应该关注 jQuery on 事件
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5