[英]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.