如何调用html doc中的函数

Nic*_*ckD 0 html javascript jquery

我创建了一个获得2个参数的命名函数.第一个参数是没有表达式的图像文件名(str).第二个参数是像素的图像高度(num).我想在html文档中显示给定高度的图像.

例如:

<div><script>showImage('test', 100);</script></div>
Run Code Online (Sandbox Code Playgroud)

我相信函数不是正确的方式.如何正确调用函数来显示任何div内的图像.

function showImage (imgfilename, imgheight) {
	var img = '';
	imgheight = typeof(imgheight) !== "undefined" ? imgheight : "64";
	imgheight = 64 + (imgheight - 64);
	img += '<img src="https://i.imgsafe.org/'+imgfilename+'.png" width="64px" height="'+imgheight+'px">';
	//console.log (img);
	return img;
}	
Run Code Online (Sandbox Code Playgroud)
body {background-color: #ccc;}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div id="img1"><script>showImage('7a622f4233', 68);</script></div>

<div id="img2"><script>showImage('7a622f4233', 80);</script></div>

<div id="img3"><script>showImage('7a5fa34d31', 60);</script></div>
Run Code Online (Sandbox Code Playgroud)

mad*_*scu 5

请尝试以下方法:

使用数据属性存储您的信息

<div class="img" data-id="7a622f4233" data-height="68"></div>

<div class="img" data-id="7a622f4233" data-height="80"></div>

<div class="img" data-id="7a5fa34d31" data-height="60"></div>
Run Code Online (Sandbox Code Playgroud)

JS:

$('.img').each(function(){
    var imgheight =$(this).attr('data-height');
    var imgfilename = $(this).attr('data-id');
    imgheight = imgheight != "" ? imgheight : "64";
    var img = '<img src="https://i.imgsafe.org/'+imgfilename+'.png" width="64px" height="'+imgheight+'px">';
 $(this).html(img);
})
Run Code Online (Sandbox Code Playgroud)