【问题标题】:Write text over div without using .text()在不使用 .text() 的情况下在 div 上写入文本
【发布时间】:2015-06-23 08:07:10
【问题描述】:

我又遇到了一个相当简单的问题,但我找不到答案。

到目前为止,我一直在使用 Jquery 函数 .text() 在动态创建的 div 上的 mouseenter 上写入文本。我开始意识到这只适用于我的 Iceweasel,但不适用于 Chrome。取而代之的是,人们建议使用 .val() 的任何地方都使用 .text(),但我似乎无法确切地弄清楚如何在我的实现中使用它,因为 div 没有以前的文本值。

请在下面找到一个简单的代码,使用 .text() 来理解问题。

(function(){
    for (var i = 0; i < 3; i++) {
        var span = document.createElement("span");
        span.innerHTML = "<img width=\"" + data.size[i][0] + "\" height=\"" + data.size[i][1] + "\" id=\"" + i + "\">";
        span.style.position = "absolute";
        span.style.left = data.coords[i][0] + "px";
        span.style.top = data.coords[i][1] + "px";
        document.body.appendChild(span);
    }
}());

for (var i=0; i<3; i++) {
    $('#' + i).mouseenter(function() { 
         $(this).text("text");  
    });
    $('#' + i).mouseleave(function() { 
         $(this).text("") 
    });
}

http://jsfiddle.net/ckpx6esj/1/

我希望有人能给我一个想法,如何应用 .val() 或完全使用其他东西来使其也适用于 chrome。

提前致以最诚挚的问候和感谢!

【问题讨论】:

  • 为什么使用 val() 不起作用?
  • 怀疑 .text() 有问题 - 可能是您的无效 ID。 1 不是有效的 id 值 - HTML id 必须以字母字符(或下划线)开头。 Chrome 等人在尝试通过该无效 ID 访问该元素时,可能无法从 DOM 中检索该元素。
  • 这是因为您忘记为您的 spans 设置 id。您不能在图像上使用.text() 方法。
  • ^ heh or that - id 被设置在&lt;img&gt;

标签: javascript jquery


【解决方案1】:

问题是你把文字放在图片标签里!

<img>Some text</img>

这是无效的 HTML,请参阅 this answer

如果您想在图片上显示文字,我建议您使用 divbackground: url(...)

Updated fiddle.

【讨论】:

    【解决方案2】:

    我认为不搞砸你的 for 循环的最聪明的方法是附加一个包含你的文本的 &lt;p&gt; 标签并在 mouseleave 上删除它:

    for (var i=0; i<3; i++){
                    $('#' + i).on("mouseenter",function() { 
                            $(this).parent().append("<p>text</p>"); 
                        });
                    $('#' + i).on("mouseleave",function() { 
                            $(this).parent().find("p").remove(); 
                    });
    }
    

    小提琴:

    http://jsfiddle.net/ckpx6esj/2/

    此外,由于您正在收听image (&lt;img&gt;) 而不是span,因此文本无法正常工作。图片没有 .text() 原型,因此如果你想使用 .text() 原型,你应该访问它的 parent()(在这种情况下是 &lt;span&gt;),但在父级上使用 .text()删除图像,因此想到了附加文本并稍后将其删除。

    【讨论】:

      【解决方案3】:

      根据规范,val() function 是设置值属性,它只对您页面上的输入字段有意义。 text() function 是改变你元素的内容。

      .val() 方法主要用于获取表单元素的值 例如输入、选择和文本区域。

      所以你应该在你的代码中使用text() 函数。

      还根据您的代码更改&lt;img&gt; 元素的文本属性。情况不妙。您应该更改&lt;span&gt; 的文本。因此,只需将您的 id 移至 span 元素即可。

      【讨论】:

      • 我正在使用 text(),但它不适用于 Chrome。这就是整个问题。
      • 我刚刚为您的整个问题添加了答案。
      【解决方案4】:

      如果您想要与 Javascript 的原生 innerHtml 等效的 jQuery,请选择 $(this).html('text');

      看看这些函数:

      http://api.jquery.com/html/

      $(this).html('text');
      

      http://api.jquery.com/append/

      $(this).append('text'); // Note that this appends instead of replaces
      

      http://api.jquery.com/val/

      $(this).val('text');
      

      或者如果您喜欢冒险:

      http://api.jquery.com/appendto/

      $('text').appendTo($(this)); // Performance penalty for creating an object out of 'text'
      

      【讨论】:

      • +1 for append 和 html,似乎是他们应该在这里使用的,imo 你不应该在 div 上使用 text 或 val
      【解决方案5】:

      首先我将使用 class 而不是 id,它将使用第二个循环保存, 另外,如果您还想拥有文本和图像,您可以这样做,但这会有点复杂我建议在包含文本的跨度中添加一些子元素,我不是为了挑战而这样做的 http://jsfiddle.net/ckpx6esj/5/

      无需更改html元素即可更改文本的简单插件

      $.fn.selectorText = function(text) {
          var str = '';
      
          this.contents().each(function() {
              if (this.nodeType === 3) {
                  if(typeof(text) === 'string'){
                      this.textContent = text;
                      return false;
                  }else{
                      str += this.textContent || this.innerText || '';
                  }
      
              }
          });
      
          return str;
      };
      
      
      var thisData = [{
          'coords' : [[100,100], [300, 300], [200, 200]],
          'size' : [[30, 30], [30, 30], [30, 30]]
      }];
      var data = thisData[0];
      
      (function(){
      
          for (var i = 0; i < 3; i ++){
              var span = document.createElement("span");
              span.setAttribute('class','spanImage');
              span.style.position = "absolute";
              span.style.left = data.coords[i][0] + "px";
              span.style.top = data.coords[i][1] + "px";
              span.innerHTML = "\n<img width=\"" + data.size[i][0] + "\" height=\"" + data.size[i][1] + "\" id=\"" + i + "\">";
              document.body.appendChild(span);
          }
      
      
      $('.spanImage')
        .on( 'mouseenter', function() {
         $(this).selectorText('text');    
        })
        .on( 'mouseleave', function() {
         $(this).selectorText('');
        });
      }());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多