考虑一下我用HTML5创建一些自定义元素
<orange-juice>...</orange-juice>
<apple-juice>...</apple-juice>
<banana-juice>...</banana-juice>
Run Code Online (Sandbox Code Playgroud)
有许多类型的果汁元素.我想用一个带有jquery的指令使用它们的后缀来选择它们.
我试过但它不起作用:
$('$=juice').html('juice'); //the .html instruction is not important
Run Code Online (Sandbox Code Playgroud)
如果我一个接一个地把它们拿走.
$('orange-juice').html('juice'); //this work
$('apple-juice').html('juice'); //this work
$('banana-juice').html('juice'); //this work
Run Code Online (Sandbox Code Playgroud)
但是这些自定义元素中有许多后缀juice.如何在一条指令中选择它们.
编辑1 确定一个公共类可以工作但是,这不是我的代码,并且有太多的这些元素逐个采用主题.但如果没有解决方案,我会做到这一点(一个月内).
你可以尝试.filter(fn)函数,这是一个preffix的例子
$('body *').filter(function(){
return this.tagName.toLowerCase().indexOf('juice') == 0;
}).html('juice');
Run Code Online (Sandbox Code Playgroud)
但是我建议你分配一个公共类,然后可以很容易地使用类选择器(".class").
后缀示例,这里我使用了endsWith()方法
jQuery(function($) {
$('body *').filter(function() {
return this.tagName.toLowerCase().endsWith('juice');
}).html('juice');
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<orange-juice>...</orange-juice>
<apple-juice>...</apple-juice>
<banana-juice>...</banana-juice>Run Code Online (Sandbox Code Playgroud)