将具有条件的动态样式添加到dom元素

时间:2014-04-22 10:53:18

标签: javascript jquery html css dom

我正在动态生成div但我想要的是添加一个锚标记,该标记显示一个垃圾图像,用于在特定div的悬停时删除该特定消息。我写了一个:悬停在类上添加背景,这工作正常,但我也想添加一个锚标记。这是我的代码::

风格

<style>
  .mail:hover {
        background-color: #cde6f7;
        /*background-image: url("/Content/images/Trash.png");*/
    }
.mail {
    float: left;
    width: 100%;
    border-bottom: solid 1px #ccc;
    padding-bottom: 10px;
    margin-top: 3px;
    cursor: pointer;
}
</style>

这里我正在创建动态div,我想添加背景颜色和垃圾图像图像到每一个我悬停

<script>
 success: function (data) {
                if (data.MessageData != null) {
                    var DataDiv = "";
                    for (var iRow = 0; iRow < data.MessageData.length; iRow++) {
                        var RowData = data.MessageData[iRow];
                        var date = new Date(parseInt(RowData.Sent_Date.substr(6)));
                        var style = '';
                        if (RowData.IsReceiver_Received == false) {
                            style = 'color:#0460C7' + '!important ';
                        }
                        DataDiv += "<div class='mail'  id='" + RowData.pkMessageId + "' onclick=ShowMessage('" + RowData.pkMessageId + "')>";
                        DataDiv += "<h3 style=" + style + ">" + RowData.Subject + "</h3>";

                        //<label class='label' style='color:red ! important;'> hi hi hi </label>

                        DataDiv += "<label style=" + style + "class='clsLbl'> From:" + RowData.Message_From + "</label>";
                        DataDiv += "<label style=" + style + "class='clsLb2'>" + date.toDateString() + "</label></div>";
                    }
                    $("#hdnSearchType").val(1);
                    $("#hdnUserType").val(1);
                }
                $("#MessageStore").html('');
                $("#MessageStore").html(DataDiv);

            },
</script>

2 个答案:

答案 0 :(得分:1)

  $(".mail").live('hover', function(e){
      $("#"+this.id).append("<a>addd</a>");               
  });

答案 1 :(得分:1)

如果我理解你的问题,你需要这样做:

  1. 在动态创建<div>的HTML时,还要在div中添加:

    DataDiv += "<a href='its-url' class='trash'></a>";

  2. 这会在动态元素中添加一个锚点。

  3. 由于您希望将此隐藏起来,只有当您将鼠标悬停在&#34; mail&#34;格,

    .trash { display: none; }
    .mail:hover .trash { display: block; }
    

    适合你。

  4. 然后,您可以使用background-image<img src="">在此锚元素中显示垃圾桶图标。