我在div div之外放置了一个div
<div id="" class="TextShow">Click</div>
<div style="">
<img src="images/file.jpg" id="2">
</div>
下面的javascript / jquery代码来获取图像路径。
$('.TextShow').click(function() {
var ImageShowed = $('#2').attr('src');
alert(ImageShowed);
});
当我点击.TextShow时,ImageShowed为NULL。
我的问题是,为什么我没有得到图像路径。
答案 0 :(得分:2)
您错过了{
并添加了额外的[
,而这里没有任何关系。
以下是您更正后的代码:
jQuery(function ($) {
$('.TextShow').click(function () { // << this was missing
var ImageShowed = $('#2').attr('src'); // << removed the extra [
alert(ImageShowed);
});
});
另外,考虑将代码包装在jQuery(function($) { ... });
中,以确保在加载DOM后执行jQuery代码。
答案 1 :(得分:1)
您有一些语法问题:
您的代码应如下所示:
$('.TextShow').click(function() {
var ImageShowed = $('#2').attr('src');
alert(ImageShowed);
});