簡體   English   中英

javascript字符串值轉換為變量

[英]javascript string value to variable

所以我有一個有趣的問題。 盡管我已經找到了解決方案,但我想知道您對此有何看法。

詳細信息:我有一個用於掃描某些ID的JavaScript前端腳本。 為了使它更易於使用,腳本將保存所有掃描的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');

現在,名稱屬性以簡單的字符串形式存儲在“ sNameAttribute”中,如下所示:“ data [Stock] [1]”或“ data [Stock] [2]”當然取決於他單擊的元素。

我沒有弄清楚如何從該字符串值獲取索引。 我不想使用“ split”或regex-filter之類的解決方法。

為了完成任務,我只向輸入添加了一些數據屬性,索引被存儲為普通變量,如下所示:

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

我的問題是,您將如何解決該問題,或者如何從存儲在名稱屬性中的字符串值“ data [Stock] [1]”中獲取索引。 我嘗試了一些eval()函數,但沒有得到有用的結果。

如果是要獲取事件發生在哪個div / button的索引,則在頁面加載時綁定onclick事件並獲取索引會不好嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM