在keyup上调用函数

时间:2018-01-10 07:52:28

标签: javascript jquery

我正在动态添加一个输入字段,您可以在其中添加加载到Iframe中的URL。

我想在点击按钮(有效)或按输入字段中的输入时添加URL(不起作用)。

不会调用该函数。那是为什么?



$( ".button-2" ).mouseup(function() {
    $("#content").append('<div><div>Please insert URL</div><br><input type="text" class="url_eingeben" value="http://"><br><button class="bestaetigen" >Confirm</button></div>');		
});

function addURL(){
    var url = $(this).prevAll('input').val();
    $(this).parent().closest('div').html('<iframe src="'+url+'" name=""></iframe>'); 
}

$( "#content" ).on("click", ".bestaetigen", addURL); // This works
$( "#content" ).on("keyup", ".url_eingeben", function(e) {
    if (e.which == 13) {
        alert("Enter has been pressed"); 
        addURL();	// This does not work
    }
});
   
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
    <div id="top">
        <div id="logo">
        ...
        </div>

        <div id="whatever">
        ...
        </div>

        <div>
            <button class="button-2">Add the input</button>
        </div>
    </div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

将方法addURL()更改为此方法(从keyup角度来看,调用$(this)将无效,因为在这种情况下它是一个文本框):

function addURL(){

   var url = $('.bestaetigen').prevAll('input').val();
   $('.bestaetigen').parent().closest('div').html('<iframe src="'+url+'" name=""></iframe>'); 
}

并替换它:

if (e.which == 13) {
    addURL; // This does not work
}

到此:

if (e.which == 13) {
    addURL();   // This does not work
}

答案 1 :(得分:1)

更改以下功能
function addURL(){
var url = $(this).prevAll('input').val();
$(this).parent().closest('div').html('<iframe src="'+url+'" name="">
</iframe>'); 
}

$( "#content" ).on("click", ".bestaetigen", addURL); // This works
$( "#content" ).on("keyup", ".url_eingeben", function(e) {
if (e.which == 13) {
    alert("Enter has been pressed"); 
    addURL();   // This does not work
}
});

要:

function addURL(obj, url){

obj.parent().closest('div').html('<iframe src="'+url+'" name=""></iframe>'); 
}

$( "#content" ).on("click", ".bestaetigen", function(e){
var url=$(this).prevAll('input').val();
    addURL($(this), url); // This will work
}
); 
$( "#content" ).on("keyup", ".url_eingeben", function(e) {

if (e.which == 13) {
var url=$(this).val();
    addURL($(this), url);    // This will work
}
});