Jquery attr方法对'onMouseEnter'不起作用

时间:2014-02-15 07:54:38

标签: javascript jquery

这是真实的情况: 正如我所说,我有12个不同的DIV和这样的页面。我已经链接了js文件 的index.html:

 <div id="images_puzzle">
   <div>
       <img />
       <p></p>
   </div>
   <div>
       <img />
       <p></p>
   </div>
   <div>
       <img />
       <p></p>
   </div>
   <div>
       <img />
       <p></p>
   </div>
   <div>
       <img />
       <p></p>
   </div>
   <div>
       <img />
       <p></p>
   </div>
   <div>
       <img />
       <p></p>
   </div>
   <div>
       <img />
       <p></p>
   </div>
   <div>
       <img />
       <p></p>
   </div>
   <div>
       <img />
       <p></p>
   </div>
   <div>
       <img />
       <p></p>
   </div>
   <div>
       <img />
       <p></p>
   </div>
       </div>


</div>

注意到我已将Jquery.js与我自己的js文件组合在一起。 这是我无法得到我想要的地方。通过将鼠标悬停在我想要调用函数的每个图像上,所有其他属性都运行良好,但这不是。

webroot.js:

function setPuzzleImages() {
// alert('loading images...');
var $index = 1;
var $IMGs = $('#images_puzzle IMG');
$IMGs.each(function () {
$(this).attr({ 'src': 'images/105-100/' + $index + '.jpg','onmouseover':'showTitle('+$index+');'});
    $index++;
});
}

function showTitle($index) {
alert('this is the'+$index+'image');
}

1 个答案:

答案 0 :(得分:2)

我唯一能看到的问题是方法showTitle可能不在全局范围内,所以试试

$myImg = $('img')
$myImg.attr({
    src: 'myPic.png'
}).mouseover(showTitle);

function showTitle() {
    alert('Hello World');
}

演示:Fiddle

如果将方法添加到全局范围

,您的ode工作正常

演示:Fiddle


基于更新

function setPuzzleImages() {
    var $IMGs = $('#images_puzzle IMG');
    $IMGs.mouseover(showTitle).attr('src', function (i) {
        return 'images/105-100/' + (i + 1) + '.jpg'
    })
}

function showTitle() {
    console.log('Hello World', this);
}
相关问题