[英]jQuery generate unique IDs
這是我所擁有的:
<a href="<?=$arItem["LINK"]?>"><?=$arItem["TEXT"]?></a>
它是一個 PHP 數組,其中包含一些鏈接。 我需要在每個鏈接的末尾添加一個額外的哈希參數#nav-link
link。
這是我嘗試的方法:
<a id="likeLink" href=""><?=$arItem["TEXT"]?></a>
<script>
$(document).ready(function () {
$("#likeLink").attr("href", <?=$arItem["LINK"]?> + "#nav-link");
});
</script>
但是這段代碼不起作用,因為 jQuery 不知道我鏈接到哪些鏈接。 所以我想我需要生成唯一的ids
,但不知道該怎么做。
我不需要一個永遠唯一/隨機的 id,只需要每頁唯一的東西,所有這些解決方案對我來說似乎太過分了,所以我想出了這個:
var uniqId = (function(){
var i=0;
return function() {
return i++;
}
})();
要生成隨機 ID,您可以使用這個。
<script type="text/javascript">
function Generator() {};
Generator.prototype.rand = Math.floor(Math.random() * 26) + Date.now();
Generator.prototype.getId = function() {
return this.rand++;
};
var idGen =new Generator();
</script>
</html>
<body>
<!-- Place this in the body of the page content -->
<button onclick="console.log(idGen.getId())">click</button>
</body>
從 v1.9 開始,jQueryUI 有一個用於創建唯一 id 的內置方法,稱為 uniqueId()。
這段代碼將為屬於 myclass 的每個元素設置一個唯一的 id。
$(".myclass").each(function () {
$(this).uniqueId();
});
請注意,至少在我的測試中,如果元素已經有一個新 ID,則不能分配新 ID。
所以這個 div 將使用上面的 Javascript 代碼獲得一個唯一的 id
<div class="myclass"/>
但這不會
<div class="myclass" id="myId"/>
有關更多信息,請參閱https://api.jqueryui.com/uniqueId/
我總是使用以下代碼來生成唯一的 ID。 幾年前我在 Stackoverflow 上發現了這個方法:
/**
* Create a random Guid.
*
* @return {String} a random guid value.
*/
newGuid: function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
function(c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
}).toUpperCase();
}
您可以在我的庫中找到其他有用的 js 助手: https : //github.com/mazong1123/neatjs
我們可以在 Underscore 中使用uniqueId()為元素創建一個唯一的 id:
唯一身份
_.uniqueId([prefix])
為需要一個的客戶端模型或 DOM 元素生成一個全局唯一的 id。 如果前綴被傳遞,id 將被附加到它。
_.uniqueId('contact_'); => 'contact_104'
假設你在某種循環中調用代碼,你可以替換
<a href="<?=$arItem["LINK"]?>"><?=$arItem["TEXT"]?></a>
和
<a href="<?=$arItem["LINK"]?>#nav-link"><?=$arItem["TEXT"]?></a>
這樣在每個鏈接的末尾添加了“#nav-link”。 根本不需要 javascript 或 jquery :D
我知道這已經一歲了,但是,OP 表示他不知道“如何”應用 ID。 這可以使用上面使用的beri rand原型輕松完成。
/// insure ALL myClass elements have a unique ID.
if(!$('.myClass').attr("id")){
$('.myClass').attr("id",idGen.getId());
console.log($('.myClass').attr("id"));
}
或使用更廣泛的畫筆:
/// insure ALL anchor tags have a unique ID.
if(!$('a').attr("id")){
$('a').attr("id",idGen.getId());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.