[英]How can I find out text position inside container element?
这是我的标记
<label class="ui_checkbox">
MyCheckbox
<input type="checkbox">
</label>
我当前正在编写一个jQuery插件,它将这个标准标记转换为一个漂亮的小部件,该小部件应将标题文本包装到一个span中并生成以下标记:
如果标题文本留在复选框中,则标记为:
<label class="ui_checkbox">
<span class="caption left">MyCheckbox</span>
<input type="checkbox">
<span class="knob"></span>
</label>
如果复选框正确,则标记为:
<label class="ui_checkbox">
<input type="checkbox">
<span class="knob"></span>
<span class="caption right">MyCheckbox</span>
</label>
问题:在我的插件代码中,如何确定原始标记“ MyCheckbox”中的标题是位于复选框的左侧还是右侧,以便放置跨度并设置其类别?
利用.nextAll()和.prevAll() :
$('.ui_checkbox').each(function(){ console.log("If checkbox is the type of one of the " + "\\nFollowing:" + $(this).find('.caption').nextAll().is(':checkbox') + "\\nPreceding:" + $(this).find('.caption').prevAll().is(':checkbox')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label class="ui_checkbox"> <span class="caption">MyCheckbox</span> <input type="checkbox"> <span class="knob"></span> </label> <hr/> <label class="ui_checkbox"> <input type="checkbox"> <span class="knob"></span> <span class="caption">MyCheckbox</span> </label>
您可以使用容器的.childNodes属性,并检查第一个孩子是TextNode(将是您的标签)还是input元素。
理想情况下,您希望找出两个元素索引并进行比较:
/// Text node, aka you label const textIdx = $('ui_checkbox')[0].childNodes.findIndex((element) => element.nodeType == Node.TextNode); /// Input node const inputIdx = $('ui_checkbox')[0].childNodes.findIndex((element) => element.nodeName == 'INPUT'); if (textIdx < inputIdx ) { // text on the left } else { // text on the right }
您可以将检查元素替换为最适合您插件的元素。
我发现的“陷阱”是围绕空白/空白文本节点,在确定文本或复选框是否是标签中的第一个子级时,必须对其进行检查,但仅忽略空白节点。 jQuery的.children()
不会加载文本节点,但是.content()
将包括纯空白的文本节点。
jsFiddle: https ://jsfiddle.net/glogan/harsx930/
这是解码器环:
它返回第一个非空白节点的.nodeType 。 对于文本(即左侧标签)为3,对于输入/对象标签(即右侧标签)为8。 您也可以/代替检查.is(":checkbox")
使其更具体,而不只是知道它是一个输入/对象标签。
// returns nodeType: Notable are: 3 is text 8 is tag like <input>
function getFirstNonWhitespaceChildObjType(obj) {
// Get the list of objects in the label
var itemType = null;
$(obj).contents().each( function( index, innerObj ) {
if (!itemType) {
if (innerObj.nodeType===3 && innerObj.data.trim().length>0) {
// string that is not whitespace;
itemType = innerObj.nodeType;
return;
};
if (innerObj.nodeType!==3) {
itemType = innerObj.nodeType;
return;
};
};
});
//
// ?? Custom code here for left/right (3/8) labels
//
console.log("FIRST .nodeType is: " + itemType );
return itemType;
};
以及遍历所有标签的函数:
jQuery(function($) {
// get list of checkboxes and call manipulation function
$( ".ui_checkbox" ).each( function( index, obj ) {
console.log("label child is: "+index +" firstType: ",
getFirstNonWhitespaceChildObjType(obj) );
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.