2012-08-07 27 views
0

好吧,這可能有點複雜,請耐心等待。使用jquery生成具有獨特hrefs的按鈕

我有HTML塊在它具有座標幾個隱藏字段:

<div id="content"> 
<div class="event"> 
    Blah blah blah 
    <input id="e1coords" class="coords" name="e1coords" type="hidden" value="-27.482359,153.024725" /> 
</div> 

<div class="event"> 
    blah blah blah 
    <input id="e2coords" class="coords" name="e2coords" type="hidden" value="-27.471134,153.0182" /> 
</div> 
<div class="event"> 
    blah blah blah 
    <input id="e3coords" class="coords" name="e3coords" type="hidden" value="-27.471667,153.023704" /> 
</div> 
    </div> 

我有一些代碼多數民衆贊成應該採取從每個隱藏輸入(座標)的值,並將其轉移到的部分href網址。 EG:

//GET COORDS 
      $(content).find('.coords').each(function() { 
       var coords = $(this).val(); 

       //CREATE BUTTON, ADD VALUE FROM 
       var input2 = '<div class="inputholder"><a class="viewmap" href="maptest.html?longlat='+ coords +' "><button>Find on Map</button></a></div>'; 
       //ATTACH BUTTON 
       $(input2).insertAfter($('#showday1 .save_event')); 
      }); 

這可以正常工作。它爲每個輸入創建一個按鈕(所以在上面的例子中創建了3個按鈕),但是每個按鈕都會打亂3次。所以從上面的HTML我得到9個按鈕,應該有3個。

任何人都可以建議一種方法來顯示每個隱藏輸入一次的按鈕嗎?

回答

1

如果你希望你的生成按鈕,每一個隱藏的輸入HTML場後右側放置(根據您的意見)我會喜歡:

$(document).ready(function() { 
      $(content).find('.coords').each(function() { 
       var coords = $(this).val(); 
       var input2 = '<div class="inputholder"><a class="viewmap" href="maptest.html?longlat='+ coords +' "><button>Find on Map</button></a></div>'; 
       $(this).after(input2); 
      }); 
}); 

正如你已經檢測到輸入(與coords類)的after jQuery函數後應每個隱藏的輸入


在另一方面右側追加所需的內容,如果你只是希望所有的按鈕被放置上的 divid=content末尾:

$(document).ready(function() { 
      var input2=""; 
      $(content).find('.coords').each(function() { 
       var coords = $(this).val(); 
       input2 += '<div class="inputholder"><a class="viewmap" href="maptest.html?longlat='+ coords +' "><button>Find on Map</button></a></div>'; 
      }); 
      $(content).after(input2); 
}); 

在該方法中,我們的所有彙總的所生成的輸入(對每個隱藏的輸入),並在結束時,我們它們附加到包裝div

1

編輯:

你的代碼也工作正常。 SEE HERE

您的頁面中有以下HTML塊嗎?

<div id="showday1"> 
    <div class="save_event">save event</div> 
</div> 

注:上面的代碼是指這條線$('#showday1 .save_event')

1

你可以試試這個:

$('#content .coords').each(function() { 
    var coords = $(this).val(); 
    //CREATE BUTTON, ADD VALUE FROM 
    var input2 = '<div class="inputholder"><a class="viewmap" href="maptest.html?longlat='+ coords +' "><button>Find on Map</button></a></div>'; 
    //ATTACH BUTTON 
     $(input2).appendTo($(this).parent()); //This append the button on the div event, change with #showday1 ... 
});