[英]Select the custom tag from button attribute
我創建了一個如下所示的按鈕元素結構
<input
type="button"
class="btn btn-primary"
name="redirect"
value="<mycustomtag data-id=15>"
title="<mycustomtag data-id=14>"
>
現在,每當DOM准備就緒時,我都試圖找出自定義元素並嘗試用字符串替換。 但我無法替換自定義元素。
我過去常常找到的片段如下
jQuery("mycustomtag").each(function(){
//process here
});
PS在以下情況下工作正常:
<div><mycustomtag data-id=20></div>
<h4><mycustomtag data-id=18></h4>
你的代碼
jQuery的( “mycustomtag”)
將嘗試找到名為mycustomtag的標簽,我理解的是你正在嘗試更換輸入屬性嗎?
嘗試下面
//if you want to get values var value = $("#btnCustom").attr("value"); var title = $("#btnCustom").attr("title"); alert(value); alert(title); //if you want to set values $("#btnCustom").attr("value","replacevalue"); $("#btnCustom").attr("title","replace value 2"); value = $("#btnCustom").attr("value"); title = $("#btnCustom").attr("title"); alert(value); alert(title);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" class="btn btn-primary" name="redirect" value="<mycustomtag data-id=15>" title="<mycustomtag data-id=14>" id="btnCustom" >
您找不到它們,因為屬性的值被視為字符串 。
要找到這些元素,您需要使用.prop()
選擇特定屬性,根據主標記選擇它們,如:
$('input').each(function() {
$(this).val();
$(this).prop('title');
});
PS在以下情況下工作正常
因為在這種情況下,它被認為是DOM中的標記元素,為什么jQuery可以通過簡單的選擇器找到它。
$('input').each(function() { console.log($(this).val()); console.log($(this).prop('title')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" class="btn btn-primary" name="redirect" value="<mycustomtag data-id=15>" title="<mycustomtag data-id=14>">
在您的第一個HTML代碼中,您要查找的是value或title屬性。 在你的第二個它是元素名稱。
要根據其值選擇元素,請使用以下語法:
$("input[value='<mycustomtag data-id=15>'")
根據標題選擇元素的工作方式類似。
如果將自定義標記放在另一個標記的屬性中,它將不會在頁面中呈現,換句話說它不會成為文檔DOM
樹的一部分,它只是屬性中的一個string
,這就是為什么當你使用jQuery("mycustomtag")
你沒有得到任何東西,但如果你把它作為div
或span
的孩子,它將會起作用。
因此,在您的特定情況下,您將需要使用.attr()
方法從此特定屬性或.val()
方法獲取它,如果它在值中。
jQuery("input").attr("title");
jQuery("input").val();
演示:
console.log(jQuery("input").attr("title")); console.log(jQuery("input").val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" class="btn btn-primary" name="redirect" value="<mycustomtag data-id=15>" title="<mycustomtag data-id=14>" >
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.