如何使这个if语句有效?

时间:2013-04-09 15:57:08

标签: javascript jquery function

我做了一个简单的例子(见演示)我正在努力的代码。我首先有一个函数来计算<p>在包装器div中的行数。根据数字(1,2或3行),包装器div应该得到一个额外的类名。

这些是我无法解决的错误:

  • 该功能在运行后停止(正如您在日志记录中看到的那样):

    if (getRows('.item p') === 1) {
    }
    
  • 当我在该函数中记录结果时,我得到Window对象,我需要特定的div来添加类,以便我的绝对链接可以正确定位

因此结果是绝对链接应该相应于行数。

是的,我知道这段代码可以用不同的方式编写(就像在我的p ...下面放置绝对链接一样)但是CMS是这样呈现它的,这将是最简单的解决方法..如果你想要查看应该如何在第一项div上添加item_1,在第二项上添加item_2等结果。

演示:http://jsfiddle.net/pndJx/

if (getRows('.item p') === 1) {
console.log('1 line');
console.log(this);
}

if (getRows('.item p') === 2) {
console.log('2 lines');
}

if (getRows('.item p') === 3) {
console.log('3 lines');
}

3 个答案:

答案 0 :(得分:2)

以这种方式编写代码

$('.item p').each(function() {
   var $this = $(this),
       rows  = getRows($this);

   console.log('%d lines', rows);

   /* add class */
   $this.parent().addClass('item_' + rows);

});

示例小提琴:http://jsfiddle.net/jSevE/

答案 1 :(得分:2)

您应该使用每个声明:http://jsfiddle.net/astynax777/pndJx/1/

$('.item p').each(function() {
    var rows = getRows(this);
    switch (rows)
    {
        case 1:
            console.log('1 line');
            break;
        case 2:
            console.log('2 lines');
            break;
        case 3:
            console.log('3 lines');
            break;
    };
});

function getRows(selector) {
    var height = $(selector).height();
    var font_size = $(selector).css('font-size');
    var scale = 1.50
    var line_height = Math.floor(parseInt(font_size) * scale);
    var rows = height / line_height;
    return Math.round(rows);
}

答案 2 :(得分:0)

听起来您希望单独为每个<div>运行该逻辑。如果是这种情况,那么我建议:

function getRows(selector, context) {
    var height = $(selector, context).height();
    var font_size = $(selector, context).css('font-size');
    var scale = 1.50
    var line_height = Math.floor(parseInt(font_size) * scale);
    var rows = height / line_height;
    return Math.round(rows);
}

$('div.item').each(function () {
    if (getRows('.item p', this) === 1) {
        // if ".item p" equals 1 then add class "item_1" to item div
        console.log('1 line');
        console.log(this); //if i log this i get window (the document), but I need to get the specific div to add the class..
    }

    //console gives back result '1 line' since true and does not continue..

    if (getRows('.item p', this) === 2) {
        // if ".item p" equals 2 then add class "item_1" to item div
        console.log('2 lines');
    }

    if (getRows('.item p', this) === 3) {
        // if ".item p" equals 3 then add class "item_1" to item div
        console.log('3 lines');
    }
});

在传递给.each() this的匿名函数的上下文中,引用了特定的<div>元素,而不是window

相关问题