【问题标题】:How to style a dynamically created div using JQuery in this function?如何在此函数中使用 JQuery 为动态创建的 div 设置样式?
【发布时间】:2011-08-12 15:15:50
【问题描述】:

这个函数有问题:

$("#contentdiv").click(function() {
    $(this).append("<div class='editable'>For some reason this div cannot be colored</div>");
})

var $currentInput = null;
$("#background_color_button").live("click", function() {
    $currentInput = null;
    if ($currentInput == null) {
        $currentInput = $(this).prev();
        $("label").html($currentInput.attr("id"));
    }
});
var editid;
$("div.editable").click(function(e) {
    e.stopPropagation();
    if ($currentInput == null)
        return;      
    var css = GetCssProperties();    
    $(this).css(css);
    $("label").html("");
});

function GetCssProperties() {
    if ($currentInput == null) return null;

    var value = $currentInput.val();
    if ($currentInput.attr("id") == "background-color") {
        return {
        "background-color": value
        }
    }
}

它允许您使用“可编辑”类更改 div 的背景颜色

首先,您单击 ID 为“#background_color_button”的 div,它将检索其上方文本输入的值,然后单击您想要样式的 div (With class="editable")应用到。

我的问题在这里:

$("#contentdiv").click(function() {
    $(this).append("<div class='editable'>For some reason this div cannot be colored</div>");
})

此函数在 ID="contentdiv" 的 div 内创建一个 class="editable" 的 div。

然而,虽然它有 class="editable",但点击 ID="background_color_button" 的 div,然后点击动态创建的 div 不会像使用 jQuery 动态加载的 div 那样改变样式。

我知道你可以使用:

.delegate('.editable', 'click', function() {
    $(this).css("background-color","red");
});

$(".editable").live("click", function() {
    $(this).css("background-color","red");
});

要做到这一点,但是当我尝试放线时:

.delegate('.editable', 'click', function() {

$(".editable").live("click", function() {

代替:

$("div.editable").click(function(e) {

该功能不再起作用。

非常感谢您,

泰勒

这是该项目的 JSfiddle 文档:

http://jsfiddle.net/TSM_mac/gJLSd/1/

【问题讨论】:

标签: jquery jquery-selectors javascript


【解决方案1】:

这是因为您在 #contentdiv div 中追加,并且事件没有冒泡。

因此,如果您从这里更改 html:

&lt;div id="contentdiv"&gt;Click here to make a div&lt;/div&gt;

到这里:

&lt;div id="contentdiv"&gt;&lt;span id='clicker'&gt;Click here to make a div&lt;/span&gt;&lt;/div&gt;

然后是来自的js:

$("#contentdiv").click(function() {
    $(this).append("<div class='editable'>For some reason this div cannot be colored</div>");
}) 

...
...

$("div.editable").click(function(e) {
     //blah blah blah
});

到这里:

$("#clicker").click(function() {
    $(this).parent().append("<div class='editable'>For some reason this div cannot be colored</div>");
})

...
...

$("div.editable").live("click",function(e) {
     //blah blah blah
});

一切正常!

【讨论】:

  • 记得添加 div:
    由于某种原因,这个 div 不能着色
    我看到事件现在没有冒泡。我做了修复,效果很好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-13
  • 2020-08-06
  • 1970-01-01
  • 2015-01-20
  • 2015-01-30
  • 1970-01-01
相关资源
最近更新 更多