2013-07-16 86 views
0

所以我有一個有趣的問題。雖然我已經找到了解決方案,但我想知道您對此有何看法。javascript字符串值到變量

詳情: 我有一個javascript frontendscript掃描一些ID。爲了使用戶更友好一些,該腳本保存所有掃描的ID並將其存儲在一個數組中。在用戶掃描了ID後,它將顯示在一個div中,並且還爲隱藏的輸入提供進一步的提交操作。 這看起來是這樣的:

<div id="scan_output"> 
    <div class="alert alert-success" style=""> 
     <button class="close single-scan-output-close" data-dismiss="alert">×</button> 
     <div>ID #66666</div> 
     <input type="hidden" value="herp;66666;derp" name="data[Stock][0]"> 
    </div> 
    <div class="alert alert-success" style=""> 
     <button class="close single-scan-output-close" data-dismiss="alert">×</button> 
     <div>ID #987654</div> 
     <input type="hidden" value="blub;987654;foo" name="data[Stock][1]"> 
    </div> 
    <div class="alert alert-success" style=""> 
     <button class="close single-scan-output-close" data-dismiss="alert">×</button> 
     <div>ID #123456</div> 
     <input type="hidden" value="foo;123456;bar" name="data[Stock][2]"> 
    </div> 
</div> 

正如你看到有輸入一些不同的值,因爲這種格式更多的信息必須上傳到後​​端。我只是添加了一些虛擬數據。

name屬性將索引存儲在第二維中,因爲您獲取數組,所以在後端也很方便。此索引也是javascript數組的索引,其中ID存儲在執行唯一檢查時,因此如果用戶兩次掃描ID,用戶將得到通知。

因此,如果用戶不小心掃描了某些錯誤,他可以通過單擊「x」按鈕將其刪除。

我的第一次嘗試看起來如下。 「關閉」事件被觸發後,我抓住這與關閉當前元素:

var $inputElement = $this.parent().find('input[type=hidden]'); 
var sNameAttribute= $inputElement.attr('name'); 

name屬性現在存儲在「sNameAttribute」作爲一個簡單的字符串,它是這樣的:「數據[股票] [ 1]「或」數據[Stock] [2]「當然取決於他點擊哪個元素。

我沒弄清楚如何從這個字符串值中獲取索引。我不想使用像「split」或regex-filter這樣的解決方法。

要完成我只是增加了一些數據屬性的輸入,其中索引存儲爲一個普通的變量的任務只是想:

<input type="hidden" value="blub;987654;foo" name="data[Stock][1]"> 

我的問題是,你將如何解決這個問題,或者如何你會得到存儲在name屬性中的字符串值「data [Stock] [1]」的索引。我嘗試了一些eval()函數,但沒有得到有用的結果。

回答

0

如果是關於獲取事件發生在哪個div /按鈕的索引,綁定頁面加載時的onclick事件並獲取索引將不會很好?

$('.single-scan-output-close').click(function (event) { 
    alert($(this).index()); 
}); 
+0

這麼簡單和聰明,我甚至沒有想過它:-) – alabama