English 中文(简体)
当一个元素添加到 DOM 时, 将一个类添加到元素中
原标题:Adding a class to element whenever an element is added to DOM

我在 document.ready() 中遵循代码如下:

$(document).ready(function(){

   $( img ).addClass( myClass );

});

Now this code works fine if I loads all the images at once, then this function adds the myClass to them(all img s). But what happens here is that whenever a new element with tag img like <img...../> is added in the DOM (via ajax or javascript), class to it does not gets added.. is it a limitation of JQuery or it provides this via some plugin or api,or we have to do it manually.

每当在DOM中添加新的“坚固”/em/强”时,我希望它的等级将设为“坚固”/坚固,

现在,我用SetTimeout () 这样在 2 秒后调用一个函数, 添加类到我的图像 :

setTimeout(function(){
  $( img ).addClass( actAsButton );
},2000);

但这是正确的方式吗? 事实上,如果我们在2秒后在DOM中添加任何新内容,这个代码也失败了。 我可以用“坚固的Interval 代替“坚固的设置 Interval < / strong”,但这在记忆使用方面成本很高。 请讲清楚 。

问题回答
$( img ).load(function() {
  $(this).addClass( actAsButton );
})
$(document).on( img ,  load , function() {
    $(this).addClass( actAsButton );
});

在您的情况下, addClass 无效,因为当 $( document).redi () 被解除时, img 元素不存在。 您应该为此使用以下代码 。

$( img ).live( load , function () {
    $( img ).addClass( actAsButton );
});




相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

jquery ui dialog opens only once

I have a button that opens a dialog when clicked. The dialog displays a div that was hidden After I close the dialog by clicking the X icon, the dialog can t be opened again.

Drop down background url in Safari Issue

selectBox.selectCSS { background: url(/Images/replacementSelectBackground.png) top left no-repeat height:auto; } I have an issue in Safari only where the image is not rendering on top ...

CSS specific for Safari

How do you target specifically safari in css with styles?

Aligning textarea in a form

Ive used the following css code to align my form elements: form { position:relative; } form input { position:absolute; left:11em; } However, the textarea element is not aligned correctly with the ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

CSS problem with page footer

I have defined my page footer in the css file as: #footer { position: absolute; height: 50px; text-align: center; background: #66CCCC; bottom: 0px; left: 0px; width: 100%; height: ...

热门标签