尝试从元素中拆分特定文本。鉴于js工作,如何简短/简单这个js?
元素html示例:
<div id="ReviewBox">
<span>(By:) Hello</span>
<div id="ReviewBox">
<span>By: Goodbye</span>
</div>
</div>
JS:
$('#ReviewBox span:contains("By:")').each(function(){
$(this).html($(this).html().split("(").join(""));
$(this).html($(this).html().split(")").join(""));
});
请Jsfiddle:http://jsfiddle.net/xSphc/60/
如何简短/简单这个js?
答案 0 :(得分:3)
您可以使用.html(function)
,也应该使用.replace()
和正则表达式删除(
和)
$('#ReviewBox span:contains("By:")').html(function(_, html) {
return html.replace(/[/(\)]/g, '');
});
$('#ReviewBox span:contains("By:")').html(function(_, html) {
return html.replace(/[/(\)]/g, '');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ReviewBox">
<span>(By:) Hello</span>
</div>
&#13;
答案 1 :(得分:1)
使用单个拆分操作/[/(\)]/g
$('#ReviewBox span:contains("By:")').each(function(){
$(this).html($(this).html().split(/[/(\)]/g).join(""));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ReviewBox">
<span>(By:) Hello</span>
<div id="ReviewBox">
<span>By: Goodbye</span>
</div>
</div>
&#13;
答案 2 :(得分:1)
使用正则表达式$(document).ready(function() {
updateMarker();
});
var mon_lat = null;
var mon_long = null;
var start_lat = null;
var start_long = null;
function updateMarker() {
// Get positions
if (navigator.geolocation) {
// Get current position
navigator.geolocation.watchPosition(
function (position) {
mon_lat = +position.coords.latitude;
mon_long = +position.coords.longitude;
initMap(mon_lat, mon_long);
}
);
// Get starting position
navigator.geolocation.getCurrentPosition(
function (position) {
start_lat = +position.coords.latitude;
start_long = +position.coords.longitude;
initMap(start_lat, start_long);
}
);
}
}
function initMap() {
// Display the map
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: mon_lat, lng: mon_long},
zoom: 10,
mapTypeControl:false
});
}
/[/(\)]/g
这是工作jsfiddle
http://jsfiddle.net/xSphc/62/