JQuery: Adicionando 5 IDs em tempo real (em vez de aulas)
-
03-07-2019 - |
Pergunta
Estou lidando com esta situação:
- Eu tenho um script de animação colorido que tem como alvo por id (não é jQuery, mas puro javascript)
- Então eu tenho uma lista dinâmica sem IDs: 'Ul' itens de listagem de algum lugar '/ul'
- E, finalmente, eu tenho o próprio jQuery (que vou usar para adicionar vários IDs em tempo real aos itens da lista: mas ainda não sei como)
Percebi que não pude acrescentar, com classes de jQuery, para os itens da lista, pois o plug -in de cores apenas pesquisam por ID (ele usa getElementById, que não têm paralelo às classes).
Devo excluir para que a função JQ addclass, que seria fácil de colocar no trabalho.
O script funcionaria apenas se eu pudesse inserir IDs na lista, 5 IDs bem definidos e dar algumas instruções posteriores no plug-in de cores externalizadas para afetá-los:
<ul>
<li><a href="" id="ontheflyone">pulled from the DB</a></li>
<li><a href="" id="ontheflytwo">pulled from the DB</a></li>
<li><a href="" id="ontheflythree">pulled from the DB</a></li>
<li><a href="" id="ontheflyfour">pulled from the DB</a></li>
<li><a href="" id="ontheflyfive">pulled from the DB</a></li>
</ul>
Então, as instruções:
document.getElementById(’id’).onmouseover = function() { 'ontheflyone','text','$color1' };
document.getElementById(’id’).onmouseout = function() { 'ontheflyone','text','$color2'};
document.getElementById(’id’).onmouseover = function() { 'ontheflytwo','text','$color1' };
document.getElementById(’id’).onmouseout = function() { 'ontheflytwo','text','$color2'};
etc.
Eu poderia alterar o próprio JavaScript do plugin, mas achei que seria mais fácil usar o jQuery para adicionar, de alguma forma, IDs no meu HTML.
O plugin de cores é uma peça incrível de código escrita por Michael LeigeberEu reproduzi o seguinte:
// main function to process the fade request //
function colorFade(id,element,start,end,steps,speed) {
var startrgb,endrgb,er,eg,eb,step,rint,gint,bint,step;
var target = document.getElementById(id);
steps = steps || 20;
speed = speed || 20;
clearInterval(target.timer);
endrgb = colorConv(end);
er = endrgb[0];
eg = endrgb[1];
eb = endrgb[2];
if(!target.r) {
startrgb = colorConv(start);
r = startrgb[0];
g = startrgb[1];
b = startrgb[2];
target.r = r;
target.g = g;
target.b = b;
}
rint = Math.round(Math.abs(target.r-er)/steps);
gint = Math.round(Math.abs(target.g-eg)/steps);
bint = Math.round(Math.abs(target.b-eb)/steps);
if(rint == 0) { rint = 1 }
if(gint == 0) { gint = 1 }
if(bint == 0) { bint = 1 }
target.step = 1;
target.timer = setInterval( function() { animateColor(id,element,steps,er,eg,eb,rint,gint,bint) }, speed);
}
// incrementally close the gap between the two colors //
function animateColor(id,element,steps,er,eg,eb,rint,gint,bint) {
var target = document.getElementById(id);
var color;
if(target.step <= steps) {
var r = target.r;
var g = target.g;
var b = target.b;
if(r >= er) {
r = r - rint;
} else {
r = parseInt(r) + parseInt(rint);
}
if(g >= eg) {
g = g - gint;
} else {
g = parseInt(g) + parseInt(gint);
}
if(b >= eb) {
b = b - bint;
} else {
b = parseInt(b) + parseInt(bint);
}
color = 'rgb(' + r + ',' + g + ',' + b + ')';
if(element == 'background') {
target.style.backgroundColor = color;
} else if(element == 'border') {
target.style.borderColor = color;
} else {
target.style.color = color;
}
target.r = r;
target.g = g;
target.b = b;
target.step = target.step + 1;
} else {
clearInterval(target.timer);
color = 'rgb(' + er + ',' + eg + ',' + eb + ')';
if(element == 'background') {
target.style.backgroundColor = color;
} else if(element == 'border') {
target.style.borderColor = color;
} else {
target.style.color = color;
}
}
}
// convert the color to rgb from hex //
function colorConv(color) {
var rgb = [parseInt(color.substring(0,2),16),
parseInt(color.substring(2,4),16),
parseInt(color.substring(4,6),16)];
return rgb;
}
Então, um milhão obrigado se alguém puder me dizer como adicionar esses IDs em tempo real, ou, talvez, como mudar o javascript para segmentar classes,
Muito Obrigado,
Jan
Solução
Então você tem um comum <ul></ul>
e quero dar a cada <li>
nele um ID único? Experimente o comando jQuery "cada":
$("li").each(function(index, element){$(element).attr("id", index);});
Isso vai dar um pau sobre tudo <li>
Elementos e atribua a todos os elementos seu índice nummerical (na matriz de elementos, o JQuery encontrou) como atributo "ID".
Outras dicas
Se você estiver usando o jQuery, você pode obter um elemento por classe usando sintaxe como esta (assumindo que a classe CSS seja chamada 'ClassName':
$(".className").mouseover(function(){
alert("something");
});
Para fazer a mesma coisa com um ID, você faria isso no jQuery:
$("#idVal").mouseover(function(){
alert("something");
});