jquery - 更换
使用 jQuery 的带有图像的元素
问题描述
我很难使用 jquery 用图像替换字符串(URL)。我希望函数在页面加载时运行并用图像替换文本字符串。我需要它来处理包含在<event-description> <p>http://example.com/pageone.html </p> </event-description>on the page.
这就是我所拥有的许多不同的“字符串”:
jQuery( document ).ready(function( $ ) {
$('.event-description p').each(function () {
string = $(this).text('http://example.com/pageone.html');
$(this).html('<img width="75" src="https://example.com/images/logo-one.jpg" alt="' + string + '" />');
string = $(this).text('http://example.com/pagetwo.html');
$(this).html('<img width="75" src="https://example.com/images/logo-two.jpg" alt="' + string + '" />');
});
});
任何帮助,将不胜感激!
解决方案
您必须使用条件来比较每个p
.
jQuery( document ).ready(function( $ ) {
$('.event-description p').each(function () {
var string = $(this).text();
if($(this).text() == 'http://example.com/pageone.html'){
$(this).html('<img width="75" src="https://via.placeholder.com/75x75?text=1" alt="' + string + '" />');
}
if($(this).text() == 'http://example.com/pagetwo.html'){
$(this).html('<img width="75" src="https://via.placeholder.com/75x75?text=2" alt="' + string + '" />');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="event-description">
<p>http://example.com/pageone.html</p>
<p>http://example.com/pagetwo.html</p>
</div>
推荐阅读
- django - 在继承和类型字段之间进行选择
- excel - 跨工作簿共享 VBA 模块
- javascript - Codemirror 中不可见的部分文本
- python - 使用 VBA 执行带有命令行参数的 python 代码
- graphql - 禁用 apollo rest 参数 camelCase 转换
- php - 使用 file_get_contents() 时 Insagram API 响应缓慢
- sql - 优化 SQL 查询获取用户信息的最后修改日期
- python - 导入 ibm_db 失败并出现 ModuleNotFoundError:没有名为“ibm_db”的模块
- laravel-5 - 在laravel 5.6中提交时找不到页面
- javascript - 如何在 URL 哈希修改时触发 Enter 按键事件?