jQuery值在html中作为id传递

时间:2016-05-06 13:31:45

标签: javascript jquery html

可以在Html中将jQuery变量作为Id传递。例如

 $(document).on('click', '.addvideo', function () {
     var dynamicID = $(this).attr('id');
});

这里我获取当前点击的id值" dynamicID"。我想将此值传递给另一个变量,如下面的

$('#'+dynamicID).change(function(){
    alert('hi');
    });

我上面试过了。但我收到错误" ReferenceError:未定义dynamicID "。如何解决这个问题?

4 个答案:

答案 0 :(得分:2)

在addvideo click事件中写入更改事件,然后只有它将绑定:

$(document).on('click', '.addvideo', function () {
     var dynamicID = $(this).attr('id');
     $('#'+dynamicID).change(function(){
        alert('hi');
     });
});

答案 1 :(得分:0)

该错误是由于您尝试从不可用的某个位置访问变量dynamicID而导致的。

JS中的变量只能在定义它们的函数中访问,换句话说就是您编写var something = 'value'的部分。

因此在您的示例中,变量dynamicID在此函数中的任何位置都可用,但不在其外部。

$(document).on('click', '.addvideo', function () {
     var dynamicID = $(this).attr('id');
});
console.log(dynamicID) //ReferenceError: dynamicID is not defined

当您尝试在函数外部访问dynamicID时,您将收到错误,因为它基本上不存在。

因此,您可以在定义它的函数内移动使用dynamicID的函数:

$(document).on('click', '.addvideo', function () {
     var dynamicID = $(this).attr('id');
     $('#'+dynamicID).change(function(){
        alert('hi');
     });
});

或者要在其他地方访问变量,您可以在函数外部定义它,在函数中为其赋值,然后从其他地方访问它。

var dynamicID;
$(document).on('click', '.addvideo', function () {
     dynamicID = $(this).attr('id');
});

console.log(dynamicID) //this will log the ID value provided the element has been clicked

答案 2 :(得分:0)

您收到该错误的原因是您处于不同的范围,这意味着不会定义dynamicID。尝试将其添加到相同的范围内,如下所示:

$(document).on('click', '.addvideo', function () {

    var dynamicID = $(this).attr('id');

    $('#'+dynamicID).change(function(){
        alert('hi');
    });

});

答案 3 :(得分:0)

好吧,我不知道你打算如何获取动态ID,但想象一下你是不是想从文本框中获取它。这是我将如何做到的。



$(document).ready(function() {
  var dynamicID = '#' + $('#yada').val();

  $(dynamicID).on('input', function(e) {
    alert('hi');
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="yada" value="yada">
&#13;
&#13;
&#13;