Замените () перед html () и добавьте «&» между двумя строками

0

Пожалуйста, ознакомьтесь с этим примером скрипта. Он ищет строки, содержащие "глюкозамин". Как я могу удалить "глюкозамин" и добавить "&", если он возвращает две строки, например:

A Item
Sulfate
B Item
Sulfate & HCl

Я получил неопределенную ошибку, используя .replace("Glucosamine","") после append.

JSON:

[{"title":"A","Ingredient":"Glucosamine Sulfate,Vitamin C"},{"title":"B","Ingredient":"Vitamin D,Glucosamine Sulfate,Glucosamine HCl,Vitamin A"}]

Код:

$.ajax({
    url: "text.json",
    success: function (data) {

        $(data.query.results.json.json).each(function (index, item) {        
            var title = item.title;
            var ingredients = item.Ingredient; 
              ingredients = ingredients.split(",");
           $.each(ingredients,function(i,ingredient){
            if (ingredient.indexOf("Glucosamine") >= 0) {
            $('.' + title+'glu').append('<h5>'+ingredient+'</h5>') 
             }
            });
        });
    },
    error: function () {}
});

HTML:

<h3>A Item</h3>
<div class="Aglu"></div>
<h3>B Item</h3>
<div class="Bglu"></div>
  • 1
    Обратите внимание, если я вас понимаю. Это эффект, который вы после? jsfiddle.net/qs5HY
  • 0
    Вы должны позвонить ingredient.replace('Glucosamine', '') прежде чем добавлять его.
Показать ещё 1 комментарий
Теги:
replace

2 ответа

2
Лучший ответ

Ответ

Проблема в том, что вы пытаетесь (насколько я могу судить) использовать replace на объекте jQuery следующим образом:

// this will not work
$('.' + title+'glu').append('<h5>'+ingredient+'</h5>').replace("Glucosamine","");

Проблема заключается в том, что replace() является функцией объекта String в javascript, и нет метода replace в объекте jQuery. То, что вы хотите сделать, - run replace() отношении переменной ingredient которая является строкой.

// this will work
$('.' + title+'glu').append('<h5>'+ingredient.replace("Glucosamine","")+'</h5>');

Не отвечать

Однако, исходя из вашего последнего комментария, я не верю, что это действительно поможет вам. Хотя это не связано с фактической проблемой, с которой вы столкнулись, я продолжу и быстро откладываю здесь, как бы я приблизился к тому, что вы на самом деле пытаетесь сделать. Я бы написал вашу функцию следующим образом:

    $(data.query.results.json.json).each(function (index, item) {        
        var title = item.title;
        var ingredients = item.Ingredient; 

        // this is good.  I  like the use of split here
        ingredients = ingredients.split(",");

        // here I would just filter the array.  Don't bother with indexOf.
        // You can just as easily use regex.  I've chosen to use an
        // actual regex pattern but you can also use something like this
        // just as easily: ingredient.match("Glucosamine");.  I just
        // chose to use regex for the sake of using i for case insensi-
        // tivity.  glucosamineBased is now an array of only the glucose
        // ingredients
        var glucosamineBased = ingredients.filter(function(ingredient){
            return ingredient.match(/glucosamine\s/i);
        });

        // now that we know which ones are actually glucose based, we
        // don't need to itterate through them.  Instead we can just jump
        // on combining them.  I use join which works the opposite as
        // split above.  After they are joined into one big happy string,
        // I strip out the glucosamine words.  Easy-peasy.  Just keep in
        // mind that you need g for global (don't just replace the first
        // one, but replace all instances of the pattern) and maybe i for
        // case insensitivity.
        $('.' + title+'glu').append('<h5>' +glucosamineBased.join(' & ').replace(/glucosamine\s/gi, '')+'</h5>');
    });

Надеюсь это поможет.

демонстрация

http://jsfiddle.net/HANvQ/

(oops... забыл демо)

1

Это сложнее добавить амперсанд, если массив содержит более одного экземпляра слова "Глюкозамин", но следующее должно сделать трюк:

$(data.query.results.json.json).each(function (index, item) {
    var title = item.title;
    var ingredients = item.Ingredient;
    ingredients = ingredients.split(",");
    var string = '';
    $.each(ingredients, function (i, ingredient) {
        if (ingredient.indexOf("Glucosamine") >= 0) {
            ingredient = ingredient.replace("Glucosamine","");
            string += (string.length == 0) ? ingredient : " & "+ingredient;
        }
    });
    $('.' + title + 'glu').append('<h5>' + string + '</h5>')
});

http://jsfiddle.net/wDyZd/2/

Ещё вопросы

Сообщество Overcoder
Наверх
Меню