JQuery在网站加载时设置变量

时间:2011-08-26 22:49:10

标签: javascript jquery

我有以下代码...我正在尝试在加载时在html中显示文本:

  var hero_text_under_photo = 'Hero 1'
  var hero_2_text_under_photo = 'Hero 2'
  var hero_3_text_under_photo = 'Hero 3'
  var hero_4_text_under_photo = 'Hero 4'

  console.log(hero_text_under_photo);
    $('hero_1_text_under_photo').setTextValue(hero_text_under_photo);
    $('hero_2_text_under_photo').setTextValue(hero_2_text_under_photo);
    $('hero_3_text_under_photo').setTextValue(hero_3_text_under_photo);
    $('hero_4_text_under_photo').setTextValue(hero_4_text_under_photo);

我可以使用console.log读取变量,但在单击它们之前我没有看到设置的值。我该如何解决这个问题?

<div id="whatsNew">
    <h2>What's New</h2>
    <ul id="topics" class="topics">
        <li class="topic tab1 topicSelected" onclick="rotator.loadIndex(0); rotator.stop()">
            <p id="hero_1_text_under_photo">
        </li>
        <li class="topic tab2" onclick="rotator.loadIndex(1); rotator.stop()">
  <p id="hero_2_text_under_photo">
        </li>
        <li class="topic tab3" onclick="rotator.loadIndex(2); rotator.stop()">
              <p id="hero_3_text_under_photo">
        </li>
        <li class="topic tab4" onclick="rotator.loadIndex(3); rotator.stop()">
              <p id="hero_4_text_under_photo">

        

2 个答案:

答案 0 :(得分:0)

您正在尝试设置hero_1_text_under_photo,hero_2_text_under_photo等的“标签”。也许您正在尝试按ID设置它们?

$('#hero_1_text_under_photo').setTextValue(hero_text_under_photo);
$('#hero_2_text_under_photo').setTextValue(hero_2_text_under_photo);
$('#hero_3_text_under_photo').setTextValue(hero_3_text_under_photo);
$('#hero_4_text_under_photo').setTextValue(hero_4_text_under_photo);

答案 1 :(得分:-1)

噢,这是我第一次在jQuery中看到方法setTextValue。它真的有吗? 同样,约瑟夫提到你的jQuery选择器是错误的。

由于hero_1_text_under_photo<p></p>,然后在其中插入一些文字,请使用text方法。

$('#hero_1_text_under_photo').text(hero_1_text_under_photo);

顺便说一句,您必须使用<p id="hero_1_text_under_photo">关闭</p>代码。