jQuery动态元素 - 未应用样式 [英] jQuery dynamic element - styling not being applied

查看:127
本文介绍了jQuery动态元素 - 未应用样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个按钮,当点击添加新段落或删除当前段落时。这是使用 jQuery 完成的。我也使用 jQuery hover 中将段落文字的颜色从黑色更改为红色。我遇到的问题是,在我添加了一个新的段落( jQuery 之后)时,悬停效果没有被应用到它。它适用于原始段落,但不适用于动态创建的段落。

I have 2 Button which when clicked either add a new paragraph or remove a current paragraph. This is done using jQuery. I am also using jQuery to change the color of the paragraph text from black to red on hover. The problem that I am having is that after I add a new paragraph with jQuery, the hover effect is not being applied to it. It works for the original paragraphs but not for the ones that are being created dynamically.

当我查看源代码的页面,我看到原始段落有内联样式应用于他们,但不是我通过 jQuery 添加的。我一直在网上寻找最后一个小时试图找到一个解决方案,但到目前为止还没有为我工作。我发现了一些类似的问题,但解决方案对我来说并不奏效,或者我没有正确应用它们。事实是,几个小时以前我从字面上开始学习 jQuery ,因此无法确定我是否修复某些内容或使其变得更糟。此外,我看过的大部分问题都是与我在PC上工作的 jQuery Mobile混淆在一起。

When I look at the source code of the page I see that the original paragraphs have inline styles applied to them but not the ones I added via jQuery. I have been looking online for the last hour trying to find a solution but so far none have worked for me. I found some similar questions but the solutions either didn't work for me or I wasn't applying them correctly. The thing is that I literally started learning jQuery a couple of hours ago and therefore cannot be sure if i'm fixing something or making it worse. Also, most of the questions I have looked at are to do with jQuery Mobile which confuses me further as i am working on my PC.

http://jsfiddle.net/2Xh75/

HTML

<button>Add line</button>
<button>Remove line</button>

<div id="p_wrap">
    <p> Original Line </p>
    <p> Original Line </p>
    <p> Original Line </p>
</div>

jQuery

$(document).ready(function(){

    //Add line   
    $("button:nth-of-type(1)").click(function(){
        $("#p_wrap").append("<p>New Line</p>");
    });

    //Remove line
    $("button:nth-of-type(2)").click(function(){
    $("p:last-of-type").remove();
    });

    //Hover effect
    $("p").hover(
      function(){
          $(this).css("color", "red");
      },
      function(){
          $(this).css("color", "black");
      }
    );

}); // Document Ready End

以下是我已经看过的一些问题:

Here are some of the questions I have already looked at:

强制jQuery Mobile重新评估动态插入内容的样式/主题

jQuery Mobile在动态添加内容后不应用样式

未在动态创建中应用的jquery样式

我提前道歉,因为这可能是一个noob问题,但它让我失望,我将不胜感激任何帮助。

I apologize in advance since this is probably a noob question but it has me stumped and I would appreciate any help.

- 谢谢你

推荐答案

你应该使用 .on ,因为它将绑定您将在DOM中动态附加的新元素

You should use .on as it will bind new elements that you will append dynamically in the DOM

$(document).on('mouseover', 'p',  function () {       
 $(this).css("color", "red");
}).on('mouseout', 'p',  function () {       
 $(this).css("color", "black");
});;

这篇关于jQuery动态元素 - 未应用样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆