Использование jquery для обновления onSelect () - PullRequest
4 голосов
/ 31 января 2011

У меня есть немного HTML-кода, который я хотел бы изменить в зависимости от того, на какую из 3 переключателей нажимает пользователь.

Вот переключатели:

<input type="radio" name="awardSwitch" value="silver" />
<input type="radio" name="awardSwitch" value="gold" />
<input type="radio" name="awardSwitch" value="platinum" />

HTMLЯ хочу обновить ниже:

<div id="BestCourseforyourGolfGame">
  <div class="floatleft">
    <textarea name="code" cols="50" rows="6">
    <a href="http://foo.com/best/best-of/#BestCourseforyourGolfGame" target="_blank">
    <img src="http://foo.com/assets/awards/2010/best-of-2010-silver.jpg" alt="Best Course for your Golf Game" border="0" width="151" height="200" /></a>
    </textarea>
  </div>
  <div class="floatright">
    <img src="http://foo.com/assets/awards/2010/best-of-2010-silver.jpg" alt="Best Course for your Golf Game" border="0" width="151" height="200" />
  </div>
</div>

В основном то, что я хочу изменить, мудрый текст в HTML, это последний бит имени изображения.В данном случае это «-silver», но мне бы хотелось, чтобы оно обновилось до «-gold» или «-platinum» в зависимости от выбранной радиокнопки.

Заранее спасибо!

Ответы [ 3 ]

4 голосов
/ 31 января 2011

Вы указываете jQuery, поэтому вот код, который обращается как к textarea, так и к дисплею div:

jQuery(document).ready(function(){
    jQuery('input[name=awardSwitch]:radio').click(function(){
        var newsrc = 'http://foo.com/assets/awards/2010/best-of-2010-'+jQuery(this).val()+'.jpg'
        var newhtml = '<a href="http://foo.com/best/best-of/#BestCourseforyourGolfGame" target="_blank">';
        newhtml += '<img src="'+newsrc+'.jpg"';
        newhtml += ' alt="Best Course for your Golf Game" border="0" width="151" height="200" /></a>';
        jQuery('#BestCourseforyourGolfGame textarea[name="code"]').val(newhtml);
        jQuery('#BestCourseforyourGolfGame .floatright img').attr('src', newsrc);
    });
});
2 голосов
/ 31 января 2011

Если вы используете jQuery .

$("[name='awardSwitch']").click(function(){
  var active_value = $(this).val();

  // replace the img src
  $("#BestCourseforyourGolfGame img").each(function(){
    var src = $(this).attr("src");
    src = src.substr(0, src.lastIndexOf("-")+1);
    $(this).attr("src", src + active_value + ".jpg");
  }); 

});

«Я не проверял это, я только доказал, что это правильно» -Knuth

1 голос
/ 31 января 2011

Попробуйте что-то вроде этого:

$(function () {
    $("[name=awardSwitch]").change(function () {
        var txtArea = $("[name=code]");
        var txtVal = txtArea.val();
        var prevTag = txtArea.data("prevTag");
        if (!prevTag || prevTag.length < 1) {
            prevTag = "silver"
        }
        var imgVal = $(this).val();
        txtVal = txtVal.replace(prevTag+".jpg", imgVal+".jpg")
        txtArea.val(txtVal);
        txtArea.data("prevTag", imgVal);
    });
});
...