当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - Javascript plugin appending duplicate data in Wordpress

问题描述:

I'm using a currency conversion plugin called curry.js that's being called on a custom Wordpress page with bootstrap tabs and advanced custom fields.

As WP loops through each tab it's appending to the list of currencies so that when you open the dropdown in the third tab you see the list of currencies repeated three times.

Here's the portion of the code curry.js is running each time:

var generateDDM = function( rates ){

output = '';

// Change all target elements to drop downs

dropDownMenu.each(function(){

for (var i in rates ) {

rate = rates[i];

output += '<option value="'+ i +'" data-rate="'+ rate +'">' + i + '</option>';

}

$( output ).appendTo( this );

});

};

I've tried creating a counter variable outside that block of code so that after it runs once and creates the list of currencies, it stores that list in a global output variable which is no longer appended to, but to no avail.

If further clarification is needed, I'm happy to provide--any help would be fantastic I've spend many hours trying to figure this out and I know it should be a very simple solution.

Thanks!

网友答案:

Solved this with a simple if statement checking the length of the output variable after each WP loop:

dropDownMenu.each(function(){
  if(output.length < 251) {
    for ( var i in rates ) {
      rate = rates[i];          
        output += '<option value="'+ i +'" data-rate="'+ rate +'">' + i + '</option>';
    }
    $( output ).appendTo( this );
  }
  else {
    $( output ).appendTo( this );
  }
});
网友答案:

In javascript the code is executed asynchronously meaning there is no guarantee that the second line of code gets executed only after the first line of code gets executed. So maybe that's why counter variable value is not visible to global output variable. For more information refer this great article Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

分享给朋友:
您可能感兴趣的文章:
随机阅读: