2017-01-18 2 views
0

У меня проблема с таргетингом. У меня 5 предметов. У них есть собственные индивидуальные значения для максимальной и минимальной температур в celcius и fahrenheit. Я должен сделать их, когда я нажимаю значок индивидуального celcius, должен изменить только их значение. Но теперь, когда я нажимаю значок celcius, он вносит изменения обо всех значениях и берет значение первого элемента. Вы можете видеть это здесь;Проблема с таргетингом при нажатии элемента item

var api_key = "dd39280551e44f1bb34221739171701&q="; 
 
var loc; 
 

 
$(document).ready(function() { 
 
    // var latitude,longitude; 
 
    
 

 
    $.getJSON('http://ipinfo.io', function(d){ 
 
    loc = d.loc.split(","); 
 

 
    var apiLink = "http://api.apixu.com/v1/forecast.json?key="; 
 
    var days5 = "&days=5"; 
 
    var api = apiLink + api_key + loc[0] +','+ loc[1] + days5; 
 

 

 
    $.getJSON(api, function(v1) { 
 

 
    
 
     var tempSwapForecast = true; 
 

 

 
     var forecastdayData = v1.forecast.forecastday; 
 

 
     var days = forecastdayData.map(function(d) { 
 
      return d.day; 
 
     }); 
 

 
     var maxtempc = days.map(function(maxc) { 
 
      return maxc.maxtemp_c; 
 
     }); 
 

 
     var mintempc = days.map(function(minc) { 
 
      return minc.mintemp_c; 
 
     }); 
 

 
     var maxtempf = days.map(function(maxf) { 
 
      return maxf.maxtemp_f; 
 
     }); 
 

 
     var mintempf = days.map(function(minf) { 
 
      return minf.mintemp_f; 
 
     }); 
 

 

 
     $('.forecasticons img').each(function(i) { 
 
      $(this).attr('src', days[i].condition.icon); 
 
     }); 
 

 
     $('.frc-temp').each(function(i) { 
 
      $(this).html(Math.round(maxtempc[i]) + "-" + Math.round(mintempc[i])); 
 
      $('.frc-degree').click(function() { 
 
       for (var j = 0; j < $(this).length; j++) { 
 
       if(tempSwapForecast===false){ 
 
        $('.frc-temp').html(Math.round(maxtempc[j]) + "-" + Math.round(mintempc[j])); 
 
        $('.frc-degree').html(" &#8451;"); 
 
        tempSwapForecast = true; 
 
       } else { 
 
        $('.frc-temp').html(Math.round(maxtempf[j]) + "-" + Math.round(mintempf[j])); 
 
        $('.frc-degree').html("&#8457;"); 
 
        tempSwapForecast = false; 
 
       } 
 

 
       } 
 
       
 

 
      }); 
 

 

 

 
     }); 
 

 

 
     $('.forecastText').each(function(i) { 
 
      $(this).html(days[i].condition.text); 
 
     }); 
 

 

 
    }); 
 
    }); 
 
});
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width"> 
 
    <title>JS Bin</title> 
 
</head> 
 
<body> 
 
<div id="other-days"> 
 
      <div class="forecastday"> 
 
      <div class="forecasticons" > 
 
       <img class="fcicon" alt="weather-icon" src=""> 
 
      </div> 
 
      <div class="forecastText"></div> 
 
      <div class="forecasttemp"> 
 
       <span class="frc-temp"></span> 
 
       <a class="frc-degree" href="#">&#8451;</a> 
 
      </div> 
 
      </div> 
 

 
      <div class="forecastday"> 
 
      <div class="forecasticons" > 
 
       <img class="fcicon" alt="weather-icon" src=""> 
 
      </div> 
 
       <div class="forecastText"></div> 
 
      <div class="forecasttemp"> 
 
       <span class="frc-temp"></span> 
 
       <a class="frc-degree" href="#">&#8451;</a> 
 
      </div> 
 
      </div> 
 

 
      <div class="forecastday"> 
 
      <div class="forecasticons" > 
 
       <img class="fcicon" alt="weather-icon" src=""> 
 
      </div> 
 
       <div class="forecastText"></div> 
 
      <div class="forecasttemp"> 
 
       <span class="frc-temp"></span> 
 
       <a class="frc-degree" href="#">&#8451;</a> 
 
      </div> 
 
      </div> 
 

 
      <div class="forecastday"> 
 
      <div class="forecasticons" > 
 
       <img class="fcicon" alt="weather-icon" src=""> 
 
      </div> 
 
       <div class="forecastText"></div> 
 
      <div class="forecasttemp"> 
 
       <span class="frc-temp"></span> 
 
       <a class="frc-degree" href="#">&#8451;</a> 
 
      </div> 
 
      </div> 
 

 
      <div class="forecastday"> 
 
      <div class="forecasticons" > 
 
       <img class="fcicon" alt="weather-icon" src=""> 
 
      </div> 
 
       <div class="forecastText"></div> 
 
      <div class="forecasttemp"> 
 
       <span class="frc-temp"></span> 
 
       <a class="frc-degree" href="#">&#8451;</a> 
 
      </div> 
 
      </div> 
 
     </div> 
 
    <script src="https://code.jquery.com/jquery-2.2.4.js"></script> 
 

 
</body> 
 
</html>

я жду вас ценен помогает.

ответ

2

Очень небольшие изменения, чтобы заставить его работать: в обработчике кликов вместо поиска по классу заполняемого поля я использую элемент clicked, чтобы найти его родительский элемент, а затем найдите класс WITHIN, который является родителем. Таким образом, становится $ (это) .parent() найти (...) Все эти изменения между линиями 53 и 59.

var api_key = "dd39280551e44f1bb34221739171701&q="; 
 
var loc; 
 

 
$(document).ready(function() { 
 
    // var latitude,longitude; 
 

 

 
    $.getJSON('http://ipinfo.io', function(d) { 
 
    loc = d.loc.split(","); 
 

 
    var apiLink = "http://api.apixu.com/v1/forecast.json?key="; 
 
    var days5 = "&days=5"; 
 
    var api = apiLink + api_key + loc[0] + ',' + loc[1] + days5; 
 

 

 
    $.getJSON(api, function(v1) { 
 

 

 
     var tempSwapForecast = true; 
 

 

 
     var forecastdayData = v1.forecast.forecastday; 
 

 
     var days = forecastdayData.map(function(d) { 
 
     return d.day; 
 
     }); 
 

 
     var maxtempc = days.map(function(maxc) { 
 
     return maxc.maxtemp_c; 
 
     }); 
 

 
     var mintempc = days.map(function(minc) { 
 
     return minc.mintemp_c; 
 
     }); 
 

 
     var maxtempf = days.map(function(maxf) { 
 
     return maxf.maxtemp_f; 
 
     }); 
 

 
     var mintempf = days.map(function(minf) { 
 
     return minf.mintemp_f; 
 
     }); 
 

 

 
     $('.forecasticons img').each(function(i) { 
 
     $(this).attr('src', days[i].condition.icon); 
 
     }); 
 

 
     $('.frc-temp').each(function(i) { 
 
     // Added a 'units' property, so the temperature 
 
     // can track what type of unit it is displaying. 
 
     $(this).data("units", "c"); 
 
     $(this).html(Math.round(maxtempc[i]) + "-" + Math.round(mintempc[i])); 
 
     }); 
 
     $('.frc-degree').on("click", function() { 
 
     // As we use the .frc-temp el often, reference it once. 
 
     var myTempEl = $(this).parent().find(".frc-temp"); 
 
     // This is the unique index of the clicked day. 
 
     var myIndex = $(".forecastday").index(
 
      $(this).parents(".forecastday") 
 
     ); 
 
     /**** 
 
     * Above, we created a data attribute on the 
 
     * .frc-temp element to store the units. By 
 
     * doing this, the element becomes self- 
 
     * contained. Here, we can toggle the units 
 
     * based on that data attribute. 
 
     ****/ 
 
     if (myTempEl.data("units") === "f") { 
 
      // First, switch the unit attribute... 
 
      myTempEl.data("units", "c"); 
 
      // Then, replace the contents of the temp el 
 
      myTempEl.html(
 
      Math.round(maxtempc[myIndex]) + 
 
      "-" + 
 
      Math.round(mintempc[myIndex])); 
 
      // Then, set the contents of this to 'c' 
 
      $(this).html(" &#8451;"); 
 
      tempSwapForecast = true; 
 
     } else { 
 
      myTempEl.data("units", "f"); 
 
      myTempEl.html(
 
      Math.round(maxtempf[myIndex]) + 
 
      "-" + 
 
      Math.round(mintempf[myIndex])); 
 
      $(this).html("&#8457;"); 
 
      tempSwapForecast = false; 
 
     } 
 

 
     }); 
 

 

 

 
     $('.forecastText').each(function(i) { 
 
     $(this).html(days[i].condition.text); 
 
     }); 
 

 

 
    }); 
 
    }); 
 
});
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width"> 
 
    <title>JS Bin</title> 
 
</head> 
 

 
<body> 
 
    <div id="other-days"> 
 
    <div class="forecastday"> 
 
     <div class="forecasticons"> 
 
     <img class="fcicon" alt="weather-icon" src=""> 
 
     </div> 
 
     <div class="forecastText"></div> 
 
     <div class="forecasttemp"> 
 
     <span class="frc-temp"></span> 
 
     <a class="frc-degree" href="#">&#8451;</a> 
 
     </div> 
 
    </div> 
 

 
    <div class="forecastday"> 
 
     <div class="forecasticons"> 
 
     <img class="fcicon" alt="weather-icon" src=""> 
 
     </div> 
 
     <div class="forecastText"></div> 
 
     <div class="forecasttemp"> 
 
     <span class="frc-temp"></span> 
 
     <a class="frc-degree" href="#">&#8451;</a> 
 
     </div> 
 
    </div> 
 

 
    <div class="forecastday"> 
 
     <div class="forecasticons"> 
 
     <img class="fcicon" alt="weather-icon" src=""> 
 
     </div> 
 
     <div class="forecastText"></div> 
 
     <div class="forecasttemp"> 
 
     <span class="frc-temp"></span> 
 
     <a class="frc-degree" href="#">&#8451;</a> 
 
     </div> 
 
    </div> 
 

 
    <div class="forecastday"> 
 
     <div class="forecasticons"> 
 
     <img class="fcicon" alt="weather-icon" src=""> 
 
     </div> 
 
     <div class="forecastText"></div> 
 
     <div class="forecasttemp"> 
 
     <span class="frc-temp"></span> 
 
     <a class="frc-degree" href="#">&#8451;</a> 
 
     </div> 
 
    </div> 
 

 
    <div class="forecastday"> 
 
     <div class="forecasticons"> 
 
     <img class="fcicon" alt="weather-icon" src=""> 
 
     </div> 
 
     <div class="forecastText"></div> 
 
     <div class="forecasttemp"> 
 
     <span class="frc-temp"></span> 
 
     <a class="frc-degree" href="#">&#8451;</a> 
 
     </div> 
 
    </div> 
 
    </div> 
 
    <script src="https://code.jquery.com/jquery-2.2.4.js"></script> 
 

 
</body> 
 

 
</html>
Так много много мелких изменений здесь:. КОП-временные элементы теперь есть атрибут data, который отслеживает, являются ли единицы farenheit или стоградусные, и способ, которым я ссылаюсь на элементы, также немного изменился.

+0

Здравствуйте, благодаря его работе, но с одной проблемой. Они имеют собственные индивидуальные ценности. Но когда я нажимаю один из них, он берет значение первого элемента. Я хочу, чтобы каждый элемент имел свою ценность. Извините, я новичок в javascript. – erenesto

+0

Отследил его, это был способ, которым использовался индекс (i или j, не помню, какой). Вместо этого я использую позицию дня div в коллекции дней, чтобы определить используемый индекс. Кроме того, tempSwapForecast вызывал некоторые нечетные проблемы с переключением - я изменил его, чтобы сохранить единицы в самом temp-элементе и переключиться на это. Удачи! – Snowmonkey

+0

Большое вам спасибо. Теперь работает. Я сказал, что я новичок в javascript, и иногда мои способы могут быть плохими. И спасибо за понятные комментарии. – erenesto

Смежные вопросы