繁体   English   中英

在jquery中遍历所有类名称为“ blah”的元素,并在函数中使用元素的内容

[英]Loop through all elements with class name 'blah' in jquery and use the contents of the element in a function

这就是我想用伪代码做的

Find all <td> Elements with Class name 'OSGridRef'
For each <td> element pass the text of that <td> element into a function called ConvertToLatLong
Update an <td> element in the same  table row that has the class name 'LatLong' with the results of the function.

我还不了解如何在常规JavaScript或jQuery中做到这一点。

有任何想法吗?

这应该做。 当您说“内容”时,我假设您的意思是里面的所有文字?

$(function() {
  $('tr:has(.OSGridRef)').each(function() {
    var content = $(this).find('.OSGridRef').text();
    var result = ConvertToLatLong($.trim(content));
    $(this).find('.LatLong').text(result);
  });
});

嗯,考虑到我们仅在使用伪代码,这并不是一件很漂亮的事情,但是这里有:

$('.OSGridRef').each(function() {
    var $t = $(this);
    $t.closest('tr').find('.LatLong').text(
        ConvertToLatLong($t.text())
    );
});

使用each元素对元素进行迭代。

$(function() {
    $('.OSGridRef').each( function() {
        var content = $(this).text(), // or .html() if you need the HTML
            latlong = ConvertToLatLong(content),
            $latlongholder = $(this).closest('tr').find('.LatLong');
        $latlongholder.text(latlong);
    });
});

在jQuery中,您可以使用选择器来查找所需的所有元素

那么您可以使用each()函数来调用“ ConverttoLatLong”函数。

要更新元素,您需要选择它(使用选择器,如前所述),然后将其修改为value / text / etc。

jQuery.com上的文档可能对您有很大帮助

$('.OSGridRef').each(function() {
  $('.LatLong').val(ConvertToLatLong($(this).val()));
})

这是我的第一个猜测,我不知道它们是否为输入或其他内容,但是如果您可以提供更多详细信息(例如html),则可以对其进行编辑

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM