将变量传递给嵌套的jQuery函数

时间:2016-06-16 14:41:42

标签: javascript jquery

我有两个输入字段,每个输入字段在填充文本时动态生成带红叉的小图像。想法是用户可以通过单击该图像来清除文本。 javascript代码完全相同,唯一的区别是图像的 alt值和输入框的名称属性

<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<script>
$( document ).ready(function() {

    $("input[type='text']").keyup(function(){
        var alt = "clear"+$(this).attr("name");
        if($(this).val() && !$("img[alt='"+alt+"']").length){
            $(this).after("<img src='images/cross.png' alt='"+alt+"'/>");
        }
    });

    $(document).on('click', 'img[alt="clearsource"]' , function(){
        $( "input[name='source']" ).val('');
        $(this).remove();
    });

    $(document).on('click', 'img[alt="clearlocation"]' , function(){
        $( "input[name='location']" ).val('');
        $(this).remove();
    });
});
</script>
</head>
<body>
    <form>
        <input type="text" name="source" placeholder="Source" /><br />
        <input type="text" name="location" placeholder="Location" />
    </form>
</body>
</html>

我想创建一个可重用的函数,通过它我可以传递两个变量,然后调用它两次。这是我的尝试,但它不起作用。有人可以帮忙吗?这是范围问题吗?

这是JSFiddle版本:https://jsfiddle.net/2bk86w4y/

<script>
$( document ).ready(function() {

    $("input[type='text']").keyup(function(){
        var alt = "clear"+$(this).attr("name");
        if($(this).val() && !$("img[alt='"+alt+"']").length){
            $(this).after("<img src='images/cross.png' alt='"+alt+"'/>");
        }
    });

    // == The function below replaces the duplicate functions in the previous code block. 
    // == Unfortunately it doesn't work. Please help :(

    function clearBox(inputname,imagealt){
        $(document).on("click", "img[alt='"+imagealt+"']" , function(){
            $( "input[name='"+inputname+"']"  ).val('');
            $(this).remove();
        });
    }

    clearBox("clearsource","source");
    clearBox("clearlocation","location");
});
</script>

非常感谢提前!

1 个答案:

答案 0 :(得分:1)

你的参数轮回错误。

https://jsfiddle.net/daveSalomon/2bk86w4y/1/

clearBox("clearsource", "source");
clearBox("clearlocation", "location"); 

// should be...

clearBox("source", "clearsource");
clearBox("location", "clearlocation");