在JavaScript函数中将CSS id作为参数传递

4
我是一名有帮助的助手,可以为您翻译文本。
我有一个CSS id,显示一个小红球和一个JAVASCRIPT函数。我想将CSS id作为参数传递给JavaScript函数。我看过很多教程,但无法弄清楚。以下是代码:
CSS代码:
#projectile{
    position: absolute;
    background-color: #ff0000;
    left:176px;
    top: 486px;
    width:10px;
    height:10px;
    border-radius: 8px;
    z-index: 9;
}

JAVASCRIPT代码

function gofish(projectile_id){
var projectile = getElementbyId(projectile_id);
start_x = projectile.offset().left;
start_y = projectile.offset().top;

function init()
{ setTimeout("gofish('projectile')", 500); }

你有 getElementbyId 函数吗?还是你实际上是指 document.getElementbyId - adeneo
看起来你正在使用jQuery的offset()函数? - adeneo
打开浏览器控制台,你会发现它对查看错误信息非常有用。 - jdigital
@adeneo,我尝试了getElementbyIddocument.getElementbyId两种方法,但都没有起作用。是的,我正在使用jQuery的offset函数。 - Shihan Khan
@user2611329 - 我也是这么想的,我已经在下面发布了一个答案。 - adeneo
3个回答

2
假设您正在使用jQuery,并且希望使用jQuery对象来使用offset()方法,因为对于普通的DOM节点,不存在这样的方法。
function gofish(projectile_id){
    var projectile = $('#' + projectile_id);
    var start_x = projectile.offset().left;
    var start_y = projectile.offset().top;
}

function init() { 
    setTimeout(function() {
        gofish('projectile');
    }, 500); 
}

这个可行。只需要将var projectile = $('#' + projectile_id);改为projectile = $('#' + projectile_id);即可。谢谢,这帮了我很多! :) - Shihan Khan
那会使变量成为全局变量,通常应该避免这样做,但如果它能正常工作,那就没问题。很高兴能帮忙! - adeneo

2

你的JavaScript代码存在一些错误。

  • getElementById应该大写'B',并且需要在document对象上调用。
  • 我认为你要查找的偏移量属性是element.offsetLeft和element.offsetTop。
  • 你可以直接在setTimeout上定义一个匿名函数来调用init(),就像adeneo建议的那样。
  • 你仍然需要在某处调用init()以使其运行。

这是更新后的JavaScript代码:

function gofish(projectile_id) {
    var projectile = document.getElementById(projectile_id);
    start_x = projectile.offsetLeft;
    start_y = projectile.offsetTop;
}

function init() {
    setTimeout(function () {
        gofish('projectile');
    }, 500);
}

init();

以下是实际代码展示: http://jsfiddle.net/JuvDX/


0

这可能会对你有所帮助。

    <!DOCTYPE html>
<html>
<head>

<script>
function myFunction(element)
{
alert(document.getElementById(element.id).value);
}
</script>
<style>
#para1
{
text-align:center;
color:red;
} 
</style>
</head>

<body>
<p id="para1" onclick="myFunction(this)" name="paragraph" >Hello World!</p>
</body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接