创建jquery函数并将其用于html元素

creating jquery functions and using them for html elements?

本文关键字:用于 html 元素 jquery 函数 创建      更新时间:2024-02-22

我试图用javascript创建这个函数,但它不起作用,我对js有点陌生,所以我不知道我在这里到底做错了什么。

代码:

<div id="test">TESTING</div>

JS:

function animateDiv(div){
var text = $('#' + div + '"').text();
var doAnimate = function() {
    $('span').each(function() {
        var that = $(this);
        setTimeout(function() {
            that.animate({ fontSize: "90px" }, 1500 )
                .animate({ fontSize: "50px" }, 1500 );
        },that.index()*100);
    });
}
$('#' + div + "'").html('');
for(i=0; i<text.length; i++) {
  $('#' + div + "'").append('<span>'+text[i]+'</span>');
    if(i==text.length-1) doAnimate();
  }
}
  // using the function here to run animation on div test from html  
 animateDiv(test);

jsfiddle在这里:http://jsfiddle.net/aA8Un/3/

现在可以使用

function animateDiv(div){
var text = $('#' + div.id).text();
var doAnimate = function() {
    $('span').each(function() {
        var that = $(this);
        setTimeout(function() {
            that.animate({ fontSize: "90px" }, 1500 )
                .animate({ fontSize: "50px" }, 1500 );
        },that.index()*100);
    });
}
$('#' + div.id).html('');
for(i=0; i<text.length; i++) {
  $('#' + div.id).append('<span>'+text[i]+'</span>');
    if(i==text.length-1) doAnimate();
  }
}
 animateDiv(test);

实际上,您试图通过这个$("#"+div)连接字符串和对象,这是错误的,您应该使用这个$("#"+div.id),这是合法的。

您必须使用单引号/双引号(如)来调用函数

animateDiv("test");

而不是

animateDiv(test);

并从您的代码中删除"

因此使其成为$('#' + div + '"')$('#' + div)

工作演示

var text = $('#' + div + '"').text();

替换为

var text = $('#' + div).text();
  1. animateDiv('test')

  2. 取代$('#' + div + '"') with $('#' + div)