javascript - 将变量传递给嵌套 jQuery 函数

标签 javascript jquery

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

<!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>

非常感谢!

最佳答案

您的参数设置错误。

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

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

// should be...

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

关于javascript - 将变量传递给嵌套 jQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37862404/

相关文章:

javascript - 如何根据文本输入过滤 div 并一起选择输入

jquery - 使用 jQuery 检测水平滚动 div 的结尾

jquery - Jssor Slider - 全宽 slider 容器中的全宽缩略图导航器可能吗?

javascript - D3 图表上的顶部标签被切断

javascript - 如何使用 jquery 将链接添加到表中?

javascript - Node.js/Grunt - 无法运行 Grunt 的 watch - 为什么?

javascript - 高度未调整 LayerSlider 5

javascript - 花式框不打开 iFrame 第二次

javascript - Dropzonejs rails 不呈现 js.erb 文件

javascript - 在 JS 中构建多维对象