2017-07-12 66 views
1

我對onclick和change有一些疑問。你能解釋一下當我想單擊我的每個div時,我應該如何使用代碼打印我的onclick而不是一個一個地總結。我的意思是我想只有1個綠色(在圖像上)瓦片,而不是總結。onclick with change javascript/JQuery

for(let i=0; i<woeid.length; i++){ 
$(".aClick"+i).click(function() { 
    $("#aClick"+i).toggle("slow", function(){ 
    }); 
}); 
}; 

HTML DIV點擊

<div class="col-sm-2"> 
<div id="backgroundImage0" class="inner-container aClick0"> 
    <p id="weather0"></p><img id="image0"> 
</div> 
</div> 

<div class="col-sm-2"> 
<div id="backgroundImage1" class="inner-container aClick1"><p 
    id="weather1"></p><img id="image1"> 
</div> 
</div> 

綠色領帶

<div class="col-md-2"> 
    <div class="inner-container moreWeather afterClick"id="aClick0"> 
    <p id="nWeather0"></p> 
    </div> 
</div> 

<div class="col-md-2"> 
<div class="inner-container moreWeather afterClick"id="aClick1"> 
    <p id="nWeather1"></p> 
</div> 
</div> 

3 clicks on 3 different divs

這是3個不同的城市點擊股利。是否可以只做一個而不是兩個或更多個顯示器。

+1

幾行HTML將更好地幫助回答這個問題。 從它的外觀你的html可以被修改,使你做得更簡單。我現在可以告訴你,如果你正確地使用你的html類,那麼for循環就不需要這樣做。 –

+1

我會建議包括所有相關的代碼,並生成一個最小完整和可驗證的示例https://stackoverflow.com/help/mcve – Steve

+0

我不知道我理解這個問題。沒有在你提供的代碼中你總結任何東西。 – Steve

回答

0

我看到可能有用的選項:

使用startWith選擇,然後分析你的類名作爲

$('[class^=aClick]') 

或使用通用的aClick類,並使用data-target屬性來指定要切換哪個div。您的代碼將成爲類似:

<div class="col-sm-2"> 
    <div id="backgroundImage0" class="inner-container aClick" data-target="aClick0"> 
     <p id="weather0"></p><img id="image0"> 
    </div> 
</div> 
<div class="col-sm-2"> 
    <div id="backgroundImage1" class="inner-container aClick" data-target="aClick1"><p id="weather1"></p><img id="image1"> 
    </div> 
</div> 

jQuery代碼應該是這樣的:

$(".aClick").click(function() { 
    var targetDiv = $(this).data("target"); 
    $('[id^="aClick"]:not([id="' + targetDiv + '"])').hide('slow'); 
    if (!$('#' + targetDiv).is('visible')) { 
    $('#' + targetDiv).show('slow'); 
    } 
}); 

jdfiddle:https://jsfiddle.net/wqnhs6dy/4/

編輯:誤解了問題的道歉,我修改劇本,以實際使用jquery選擇器startsWith(^ =)和:not()在一起時隱藏其他divs當使用jquery選擇器startsWith(^ =)和:not()時

+0

我的意思是你可以有2個紅色領帶。我只需要一個。當我點擊_weather0_時,它會打印** moreWeather0 **,但如果我點擊_weather0_,那麼_weather1_ ** moreWeather0 **表單weather1將更改爲** moreWeather1 **,而不是其中的兩個。 – Matt

+0

對,我首先弄錯了,但我只是用隱藏其他div的解決方案更新了我的答案,只顯示了你想要的一個。這應該是一個體面的基礎,希望實現你自己的解決方案。 – Jako

+0

非常感謝!它現在正確地工作。 – Matt

0

我一般做這個用CSS類的組合和jQuery

$("div[class^='aClick']").click(function(e){ 
    //remove all the visible green stuff 
    $(".moreWeather.afterClick").removeClass("afterClick"); 
    //add the one back you want, you can use $(this) to reference the DIV you clicked. 
}); 

,如果您選擇,您可以動畫的CSS類的添加或刪除,但在其最簡單的形式,並沒有額外的信息,這是最好的方向,我可以爲你指明