获取<a> tag from one function to another

时间:2016-03-30 09:33:39

标签: javascript jquery html json ajax

I am very new in javascript/jQuery so please bear with me if my question will be too easy for you and too difficult for me.
This is from a function, I just don't post the complete codes since it will be too long.

And I have another function which also have an ajax and I want to pass get the ID of the <a> tag:

function someName() {
  jQuery.ajax({
    type: 'POST',
    url: 'thisisprivate.aspx',
    data: {
      action: 'MyAction',
      word: 'Wednesday',
      count: '4',
      page: '1'
    },
    success: function(data) {
      var json = jQuery.parseJSON(data);
      var htmlInfo = '';
      for (i = 0; i < json.length; i++) {
        var htmlCode = '<a href="#/app/video?id=' + json[i].bcid + json[i].name + '" class="list" id="' + json[i].bcid + '"></a>';
        htmlInfo = htmlInfo + htmlCode;
      }

      jQuery('#WMVideoxx').html(htmlInfo);
    }
  });
}

and

function VideoDiv() {
  jQuery.ajax({
    type: 'POST',
    url: 'thisisprivate.aspx',
    data: {
      action: 'actionNameHere',
      idorname: id //I Want to pass the ID here
    });
}

3 个答案:

答案 0 :(得分:2)

你在做的是:

jQuery('a').click(function() {
    VideoDiv(jQuery(this).attr('id'));
});

由于动态生成<a>标记的性质且事件未注册,因此无效。考虑委派活动(有关详细信息,请参阅Understanding Event Delegation):

jQuery(document).on("click", 'a', function() {
    VideoDiv(jQuery(this).attr('id'));
});

以上代码有效,但会委托文档中的所有<a>。相反,添加一个唯一标识它的类或其他东西。并以这种方式称呼它:

jQuery(document).on("click", 'a.class', function() {
    VideoDiv(jQuery(this).attr('id'));
});

关于上述代码委托的另一个问题是,最好使用最接近的静态父而不是document。由于我不了解HTML结构,因此我使用了document:)

此外,正如Ismael Miguel所述,最好使用id获取this.id

jQuery(".static-parent").on("click", '.class', function () {
    VideoDiv(this.id);
});

以上是最好的代码。

此外,已经再次指出,为了获得更好的性能,您可以用以下代码替换代码:

setTimeout(
  (function () {
    VideoDiv(this.id);
  }).bind(this), 10
);

这将让jQuery处理下一个偶数处理程序,并将在接下来的10ms内执行此代码(如果可用)。

答案 1 :(得分:1)

试试这个:您可以在创建时点击a标记,然后传递this对象,这只是a标记元素,请参阅下面的代码

 var htmlCode = '<a href="#/app/video?id='+json[i].bcid+json[i].name+'" class="list" id="'+ json[i].bcid +'" onclick="VideoDiv(this)"></a>';

现在在javascript函数中进行以下更改

function VideoDiv(anchor)
{
    jQuery.ajax({
            type: 'POST',
            url: 'thisisprivate.aspx',
            data: {
                action: 'actionNameHere',
                idorname: anchor.id //pass id here from anchor object
            }
        });
}

注意:上述ajax调用中的数据属性不完整,请更正。

答案 2 :(得分:1)

onclick="function();"与您的锚点一起使用,并在函数中传递您想要的参数

你的htmlcode应该是这样的

<a href="#/app/video?id=' + json[i].bcid + json[i].name + '" class="list" id="' + json[i].bcid + '" onclick="VideoDiv('+json[i].bcid+');"></a>

您的VideoDiv功能

function VideoDiv(id) 
{
   //your ajax goes here
}